@botpress/sdk 0.6.15 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import { z } from 'zod';
2
- export declare const botOperationSchema: z.ZodEnum<["event_received", "register", "unregister", "ping", "action_triggered"]>;
1
+ import { z } from '@bpinternal/zui';
2
+ export declare const botOperationSchema: import("@bpinternal/zui").ZodEnum<["event_received", "register", "unregister", "ping", "action_triggered"]>;
3
3
  export type BotOperation = z.infer<typeof botOperationSchema>;
4
4
  export type BotContext = {
5
5
  botId: string;
@@ -1,5 +1,5 @@
1
+ import { z } from '@bpinternal/zui';
1
2
  import type { Server } from 'node:http';
2
- import { z } from 'zod';
3
3
  import { SchemaDefinition } from '../schema';
4
4
  import { AnyZodObject, Cast } from '../type-utils';
5
5
  import { BaseIntegrations } from './generic';
package/dist/index.d.ts CHANGED
@@ -1,11 +1,6 @@
1
1
  export * as messages from './message';
2
2
  export * from './const';
3
3
  export * from './serve';
4
+ export * from './zui';
4
5
  export { IntegrationDefinition, IntegrationDefinitionProps, IntegrationImplementation as Integration, IntegrationImplementationProps as IntegrationProps, IntegrationContext, IntegrationSpecificClient, } from './integration';
5
6
  export { Bot, BotProps, BotContext, BotSpecificClient, IntegrationInstance } from './bot';
6
- /**
7
- * @deprecated Infer type of integration message handlers instead
8
- */
9
- export type AckFunction = (props: {
10
- tags: Record<string, string>;
11
- }) => Promise<void>;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var J=Object.create;var v=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var X=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty;var R=(t,e)=>{for(var n in e)v(t,n,{get:e[n],enumerable:!0})},O=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of V(e))!Y.call(t,o)&&o!==n&&v(t,o,{get:()=>e[o],enumerable:!(r=Q(e,o))||r.enumerable});return t};var D=(t,e,n)=>(n=t!=null?J(X(t)):{},O(e||!t||!t.__esModule?v(n,"default",{value:t,enumerable:!0}):n,t)),ee=t=>O(v({},"__esModule",{value:!0}),t);var we={};R(we,{Bot:()=>S,BotSpecificClient:()=>u,Integration:()=>x,IntegrationDefinition:()=>B,IntegrationSpecificClient:()=>T,botIdHeader:()=>h,botUserIdHeader:()=>E,configurationHeader:()=>m,integrationIdHeader:()=>w,messages:()=>P,operationHeader:()=>y,parseBody:()=>p,serve:()=>f,typeHeader:()=>U,webhookIdHeader:()=>M});module.exports=ee(we);var P={};R(P,{defaults:()=>ce});var a=require("zod"),g=a.z.string().min(1),te=a.z.object({text:g}),ne=a.z.object({markdown:g}),oe=a.z.object({imageUrl:g}),se=a.z.object({audioUrl:g}),re=a.z.object({videoUrl:g}),ae=a.z.object({fileUrl:g,title:g.optional()}),ie=a.z.object({latitude:a.z.number(),longitude:a.z.number(),address:a.z.string().optional(),title:a.z.string().optional()}),G=a.z.object({title:g,subtitle:g.optional(),imageUrl:g.optional(),actions:a.z.array(a.z.object({action:a.z.enum(["postback","url","say"]),label:g,value:g}))}),F=a.z.object({text:g,options:a.z.array(a.z.object({label:g,value:g}))}),ge=a.z.object({items:a.z.array(G)}),ce={text:{schema:te},markdown:{schema:ne},image:{schema:oe},audio:{schema:se},video:{schema:re},file:{schema:ae},location:{schema:ie},carousel:{schema:ge},card:{schema:G},dropdown:{schema:F},choice:{schema:F}};var h="x-bot-id",E="x-bot-user-id",w="x-integration-id",M="x-webhook-id",m="x-bp-configuration",y="x-bp-operation",U="x-bp-type";var _=require("node:http");var d=console;function p(t){if(!t.body)throw new Error("Missing body");return JSON.parse(t.body)}async function f(t,e=8072,n=Te){let r=(0,_.createServer)(async(o,s)=>{try{let i=await pe(o);if(i.path==="/health"){s.writeHead(200).end("ok");return}let c=await t(i);s.writeHead(c?.status??200,c?.headers??{}).end(c?.body??"{}")}catch(i){d.error("Error while handling request",{error:i?.message??"Internal error occured"}),s.writeHead(500).end(JSON.stringify({error:i?.message??"Internal error occured"}))}});return r.listen(e,()=>n(e)),r}async function pe(t){let e=await de(t),n={};for(let o=0;o<t.rawHeaders.length;o+=2){let s=t.rawHeaders[o].toLowerCase(),i=t.rawHeaders[o+1];n[s]=i}let r=new URL(t.url??"",t.headers.host?`http://${t.headers.host}`:"http://botpress.cloud");return{body:e,path:r.pathname,query:le(r.search,"?"),headers:n,method:t.method?.toUpperCase()??"GET"}}function le(t,e){return t.indexOf(e)===0?t.slice(e.length):t}async function de(t){return new Promise((e,n)=>{if(t.method!=="POST"&&t.method!=="PUT"&&t.method!=="PATCH")return e(void 0);let r="";t.on("data",o=>r+=o.toString()),t.on("error",o=>n(o)),t.on("end",()=>e(r))})}function Te(t){d.info(`Listening on port ${t}`)}var L=require("zod");var ue=L.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]),K=t=>{let e=t[h],n=t[E],r=t[w],o=t[M],s=t[m],i=ue.parse(t[y]);if(!e)throw new Error("Missing bot headers");if(!n)throw new Error("Missing bot user headers");if(!r)throw new Error("Missing integration headers");if(!o)throw new Error("Missing webhook headers");if(!s)throw new Error("Missing configuration headers");if(!i)throw new Error("Missing operation headers");return{botId:e,botUserId:n,integrationId:r,webhookId:o,operation:i,configuration:s?JSON.parse(Buffer.from(s,"base64").toString("utf-8")):{}}};var B=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.icon=e.icon,this.readme=e.readme,this.title=e.title,this.identifier=e.identifier,this.description=e.description,this.configuration=e.configuration,this.events=e.events,this.actions=e.actions,this.channels=e.channels,this.states=e.states,this.user=e.user,this.secrets=e.secrets,this.entities=e.entities}name;version;title;description;icon;readme;configuration;events;actions;channels;states;user;secrets;identifier;entities};var C=require("@botpress/client");var T=class{constructor(e){this.client=e}createConversation=e=>this.client.createConversation(e);getConversation=e=>this.client.getConversation(e);listConversations=e=>this.client.listConversations(e);getOrCreateConversation=e=>this.client.getOrCreateConversation(e);updateConversation=e=>this.client.updateConversation(e);deleteConversation=e=>this.client.deleteConversation(e);listParticipants=e=>this.client.listParticipants(e);addParticipant=e=>this.client.addParticipant(e);getParticipant=e=>this.client.getParticipant(e);removeParticipant=e=>this.client.removeParticipant(e);createEvent=e=>this.client.createEvent(e);getEvent=e=>this.client.getEvent(e);listEvents=e=>this.client.listEvents(e);createMessage=e=>this.client.createMessage(e);getOrCreateMessage=e=>this.client.getOrCreateMessage(e);getMessage=e=>this.client.getMessage(e);updateMessage=e=>this.client.updateMessage(e);listMessages=e=>this.client.listMessages(e);deleteMessage=e=>this.client.deleteMessage(e);createUser=e=>this.client.createUser(e);getUser=e=>this.client.getUser(e);listUsers=e=>this.client.listUsers(e);getOrCreateUser=e=>this.client.getOrCreateUser(e);updateUser=e=>this.client.updateUser(e);deleteUser=e=>this.client.deleteUser(e);getState=e=>this.client.getState(e);setState=e=>this.client.setState(e);getOrSetState=e=>this.client.getOrSetState(e);patchState=e=>this.client.patchState(e);configureIntegration=e=>this.client.configureIntegration(e)};var k=D(require("util")),b=t=>{if(process.env.BP_LOG_FORMAT==="json")return JSON.stringify({msg:k.default.format(...t),visible_to_bot_owner:!0});{let[e,...n]=t;return k.default.format(`[For Bot Owner] ${e}`,...n)}},j={forBot:()=>({info:(...t)=>{console.info(b(t))},warn:(...t)=>{console.warn(b(t))},error:(...t)=>{console.error(b(t))},debug:(...t)=>{console.debug(b(t))}})};var q=t=>async e=>{let n=K(e.headers),r=new T(new C.Client({botId:n.botId,integrationId:n.integrationId})),o={ctx:n,req:e,client:r,logger:j,instance:t};try{let s;switch(n.operation){case"webhook_received":s=await he(o);break;case"register":s=await me(o);break;case"unregister":s=await ye(o);break;case"message_created":s=await Be(o);break;case"action_triggered":s=await be(o);break;case"ping":s=await Ie(o);break;case"create_user":s=await fe(o);break;case"create_conversation":s=await ve(o);break;default:throw new Error(`Unknown operation ${n.operation}`)}return s?{...s,status:s.status??200}:{status:200}}catch(s){if(s instanceof C.RuntimeError)return{status:s.code,body:JSON.stringify(s.toJSON())};throw s}},Ie=async t=>{},he=async({client:t,ctx:e,req:n,logger:r,instance:o})=>{let{req:s}=p(n);return o.webhook({client:t,ctx:e,req:s,logger:r})},me=async({client:t,ctx:e,req:n,logger:r,instance:o})=>{if(!o.register)return;let{webhookUrl:s}=p(n);await o.register({client:t,ctx:e,webhookUrl:s,logger:r})},ye=async({client:t,ctx:e,req:n,logger:r,instance:o})=>{if(!o.unregister)return;let{webhookUrl:s}=p(n);await o.unregister({ctx:e,webhookUrl:s,client:t,logger:r})},fe=async({client:t,ctx:e,req:n,logger:r,instance:o})=>{if(!o.createUser)return;let{tags:s}=p(n);return await o.createUser({ctx:e,client:t,tags:s,logger:r})},ve=async({client:t,ctx:e,req:n,logger:r,instance:o})=>{if(!o.createConversation)return;let{channel:s,tags:i}=p(n);return await o.createConversation({ctx:e,client:t,channel:s,tags:i,logger:r})},Be=async({ctx:t,req:e,client:n,logger:r,instance:o})=>{let{conversation:s,user:i,type:c,payload:I,message:l}=p(e),A=o.channels[s.channel];if(!A)throw new Error(`Channel ${s.channel} not found`);let H=A.messages[c];if(!H)throw new Error(`Message of type ${c} not found in channel ${s.channel}`);await H({ctx:t,conversation:s,message:l,user:i,type:c,client:n,payload:I,ack:async({tags:W})=>{await n.updateMessage({id:l.id,tags:W})},logger:r})},be=async({req:t,ctx:e,client:n,logger:r,instance:o})=>{let{input:s,type:i}=p(t);if(!i)throw new Error("Missing action type");let c=o.actions[i];if(!c)throw new Error(`Action ${i} not found`);let I=await c({ctx:e,input:s,client:n,type:i,logger:r});return{body:JSON.stringify({output:I})}};var x=class{props;actions;channels;register;unregister;createUser;createConversation;webhook;constructor(e){this.props=e,this.actions=e.actions,this.channels=e.channels,this.register=e.register,this.unregister=e.unregister,this.createUser=e.createUser,this.createConversation=e.createConversation,this.webhook=e.handler}handler=q(this);start=e=>f(this.handler,e)};var Z=D(require("@botpress/client"));var u=class{constructor(e){this.client=e}getConversation=e=>this.client.getConversation(e);listConversations=e=>this.client.listConversations(e);updateConversation=e=>this.client.updateConversation(e);deleteConversation=e=>this.client.deleteConversation(e);listParticipants=e=>this.client.listParticipants(e);addParticipant=e=>this.client.addParticipant(e);getParticipant=e=>this.client.getParticipant(e);removeParticipant=e=>this.client.removeParticipant(e);getEvent=e=>this.client.getEvent(e);listEvents=e=>this.client.listEvents(e);createMessage=e=>this.client.createMessage(e);getOrCreateMessage=e=>this.client.getOrCreateMessage(e);getMessage=e=>this.client.getMessage(e);updateMessage=e=>this.client.updateMessage(e);listMessages=e=>this.client.listMessages(e);deleteMessage=e=>this.client.deleteMessage(e);getUser=e=>this.client.getUser(e);listUsers=e=>this.client.listUsers(e);updateUser=e=>this.client.updateUser(e);deleteUser=e=>this.client.deleteUser(e);getState=e=>this.client.getState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));setState=e=>this.client.setState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));getOrSetState=e=>this.client.getOrSetState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));patchState=e=>this.client.patchState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));callAction=e=>this.client.callAction(e);createConversation=e=>this.client.createConversation(e);getOrCreateConversation=e=>this.client.getOrCreateConversation(e);createUser=e=>this.client.createUser(e);getOrCreateUser=e=>this.client.getOrCreateUser(e)};var $=require("zod");var Ce=$.z.enum(["event_received","register","unregister","ping","action_triggered"]),N=t=>{let e=t[h],n=t[m],r=t[U],o=Ce.parse(t[y]);if(!e)throw new Error("Missing bot headers");if(!r)throw new Error("Missing type headers");if(!n)throw new Error("Missing configuration headers");if(!o)throw new Error("Missing operation headers");return{botId:e,operation:o,type:r,configuration:n?JSON.parse(Buffer.from(n,"base64").toString("utf-8")):{}}};var z=t=>async e=>{let n=N(e.headers);n.operation!=="ping"&&d.info(`Received ${n.operation} operation for bot ${n.botId} of type ${n.type}`);let r=new u(new Z.Client({botId:n.botId})),o={req:e,ctx:n,client:r,instance:t};switch(n.operation){case"action_triggered":throw new Error(`Operation ${n.operation} not supported yet`);case"event_received":await Ee(o);break;case"register":await Se(o);break;case"unregister":await Pe(o);break;case"ping":await xe(o);break;default:throw new Error(`Unknown operation ${n.operation}`)}return{status:200}},xe=async t=>{},Se=async t=>{},Pe=async t=>{},Ee=async({ctx:t,req:e,client:n,instance:r})=>{d.debug(`Received event ${t.type}`);let o=p(e),s=o.event;switch(t.type){case"message_created":let i={user:s.payload.user,conversation:s.payload.conversation,message:s.payload.message,states:s.payload.states,event:s};await Promise.all(r.messageHandlers.map(l=>l({client:n,ctx:t,...i})));break;case"state_expired":let c={state:s.payload.state};await Promise.all(r.stateExpiredHandlers.map(l=>l({client:n,ctx:t,...c})));break;default:let I={event:o.event};await Promise.all(r.eventHandlers.map(l=>l({client:n,ctx:t,...I})))}};var S=class{_state={messageHandlers:[],eventHandlers:[],stateExpiredHandlers:[]};props;constructor(e){this.props=e}message=e=>{this._state.messageHandlers.push(e)};event=e=>{this._state.eventHandlers.push(e)};stateExpired=e=>{this._state.stateExpiredHandlers.push(e)};handler=z(this._state);start=e=>f(this.handler,e)};0&&(module.exports={Bot,BotSpecificClient,Integration,IntegrationDefinition,IntegrationSpecificClient,botIdHeader,botUserIdHeader,configurationHeader,integrationIdHeader,messages,operationHeader,parseBody,serve,typeHeader,webhookIdHeader});
1
+ "use strict";var ee=Object.create;var S=Object.defineProperty;var te=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var oe=Object.getPrototypeOf,se=Object.prototype.hasOwnProperty;var k=(t,e)=>{for(var n in e)S(t,n,{get:e[n],enumerable:!0})},x=(t,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ne(e))!se.call(t,s)&&s!==n&&S(t,s,{get:()=>e[s],enumerable:!(a=te(e,s))||a.enumerable});return t},p=(t,e,n)=>(x(t,e,"default"),n&&x(n,e,"default")),j=(t,e,n)=>(n=t!=null?ee(oe(t)):{},x(e||!t||!t.__esModule?S(n,"default",{value:t,enumerable:!0}):n,t)),re=t=>x(S({},"__esModule",{value:!0}),t);var T={};k(T,{Bot:()=>U,BotSpecificClient:()=>y,Integration:()=>M,IntegrationDefinition:()=>P,IntegrationSpecificClient:()=>I,botIdHeader:()=>b,botUserIdHeader:()=>D,configurationHeader:()=>v,integrationIdHeader:()=>O,messages:()=>A,operationHeader:()=>B,parseBody:()=>u,serve:()=>C,studioComponentDefinitions:()=>_,typeHeader:()=>R,webhookIdHeader:()=>H,z:()=>o.z});module.exports=re(T);var A={};k(A,{defaults:()=>me});var g={};k(g,{default:()=>ae,studioComponentDefinitions:()=>_,z:()=>o.z});var o=require("@bpinternal/zui");p(g,require("@bpinternal/zui"));var d=o.z.object({allowDynamicVariable:o.z.boolean().optional(),horizontal:o.z.boolean().optional()}),_={string:{textInput:{id:"textInput",params:d.extend({multiLine:o.z.boolean().optional(),growVertically:o.z.boolean().optional(),suggestions:o.z.array(o.z.string()).optional()})},dropdown:{id:"dropdown",params:d.extend({filterable:o.z.boolean().optional()})},radiogroup:{id:"radiogroup",params:d.extend({})},datepicker:{id:"datepicker",params:d.extend({dateFormat:o.z.string().optional(),minDate:o.z.string().optional(),maxDate:o.z.string().optional(),defaultTimezone:o.z.string().optional(),disableTimezoneSelection:o.z.boolean().optional(),highlightCurrentDay:o.z.boolean().optional(),showShortcutButtons:o.z.boolean().optional(),showOutsideDaysOfMonth:o.z.boolean().optional(),firstDayOfWeek:o.z.number().optional(),canChangeMonth:o.z.boolean().optional(),showWeekNumbers:o.z.boolean().optional()})},timepicker:{id:"timepicker",params:d.extend({useAMPM:o.z.boolean().optional(),timeFormat:o.z.string().optional(),minTime:o.z.string().optional(),maxTime:o.z.string().optional(),showArrowButtons:o.z.boolean().optional(),precision:o.z.enum(["minute","second","millisecond"]).optional()})},variablepicker:{id:"variablepicker",params:o.z.object({type:o.z.enum(["any","string","number","boolean","object","pattern","date","array","target","time","enum"]),horizontal:o.z.boolean().optional()})},richTextEditor:{id:"richTextEditor",params:o.z.object({allowDynamicVariable:o.z.boolean().optional(),resizable:o.z.boolean().optional()})},JSONInput:{id:"JSONInput",params:d.extend({showPreview:o.z.boolean().optional(),showValidationError:o.z.boolean().optional()})},fileInput:{id:"fileInput",params:d.extend({fileTypes:o.z.array(o.z.enum(["image","audio","video"])).optional(),showUploadedFiles:o.z.boolean().optional()})}},number:{numberInput:{id:"numberInput",params:d.extend({allowNumericCharactersOnly:o.z.boolean().optional(),stepSize:o.z.number().optional()})},slider:{id:"slider",params:o.z.object({horizontal:o.z.boolean().optional(),stepSize:o.z.number().optional()})}},boolean:{switch:{id:"switch",params:d}},array:{optionList:{id:"optionList",params:d},stringList:{id:"stringList",params:d}},object:{collapsible:{id:"collapsible",params:o.z.object({defaultOpen:o.z.boolean().optional()})}}},ae=o.z;var c=o.z.string().min(1),ie=o.z.object({text:c}),ge=o.z.object({markdown:c}),ce=o.z.object({imageUrl:c}),pe=o.z.object({audioUrl:c}),le=o.z.object({videoUrl:c}),de=o.z.object({fileUrl:c,title:c.optional()}),ue=o.z.object({latitude:o.z.number(),longitude:o.z.number(),address:o.z.string().optional(),title:o.z.string().optional()}),q=o.z.object({title:c,subtitle:c.optional(),imageUrl:c.optional(),actions:o.z.array(o.z.object({action:o.z.enum(["postback","url","say"]),label:c,value:c}))}),K=o.z.object({text:c,options:o.z.array(o.z.object({label:c,value:c}))}),Te=o.z.object({items:o.z.array(q)}),me={text:{schema:ie},markdown:{schema:ge},image:{schema:ce},audio:{schema:pe},video:{schema:le},file:{schema:de},location:{schema:ue},carousel:{schema:Te},card:{schema:q},dropdown:{schema:K},choice:{schema:K}};var b="x-bot-id",D="x-bot-user-id",O="x-integration-id",H="x-webhook-id",v="x-bp-configuration",B="x-bp-operation",R="x-bp-type";var z=require("node:http");var h=console;function u(t){if(!t.body)throw new Error("Missing body");return JSON.parse(t.body)}async function C(t,e=8072,n=fe){let a=(0,z.createServer)(async(s,r)=>{try{let i=await he(s);if(i.path==="/health"){r.writeHead(200).end("ok");return}let l=await t(i);r.writeHead(l?.status??200,l?.headers??{}).end(l?.body??"{}")}catch(i){h.error("Error while handling request",{error:i?.message??"Internal error occured"}),r.writeHead(500).end(JSON.stringify({error:i?.message??"Internal error occured"}))}});return a.listen(e,()=>n(e)),a}async function he(t){let e=await ye(t),n={};for(let s=0;s<t.rawHeaders.length;s+=2){let r=t.rawHeaders[s].toLowerCase(),i=t.rawHeaders[s+1];n[r]=i}let a=new URL(t.url??"",t.headers.host?`http://${t.headers.host}`:"http://botpress.cloud");return{body:e,path:a.pathname,query:Ie(a.search,"?"),headers:n,method:t.method?.toUpperCase()??"GET"}}function Ie(t,e){return t.indexOf(e)===0?t.slice(e.length):t}async function ye(t){return new Promise((e,n)=>{if(t.method!=="POST"&&t.method!=="PUT"&&t.method!=="PATCH")return e(void 0);let a="";t.on("data",s=>a+=s.toString()),t.on("error",s=>n(s)),t.on("end",()=>e(a))})}function fe(t){h.info(`Listening on port ${t}`)}p(T,g,module.exports);var N=require("@bpinternal/zui");var be=N.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]),$=t=>{let e=t[b],n=t[D],a=t[O],s=t[H],r=t[v],i=be.parse(t[B]);if(!e)throw new Error("Missing bot headers");if(!n)throw new Error("Missing bot user headers");if(!a)throw new Error("Missing integration headers");if(!s)throw new Error("Missing webhook headers");if(!r)throw new Error("Missing configuration headers");if(!i)throw new Error("Missing operation headers");return{botId:e,botUserId:n,integrationId:a,webhookId:s,operation:i,configuration:r?JSON.parse(Buffer.from(r,"base64").toString("utf-8")):{}}};var P=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.icon=e.icon,this.readme=e.readme,this.title=e.title,this.identifier=e.identifier,this.description=e.description,this.configuration=e.configuration,this.events=e.events,this.actions=e.actions,this.channels=e.channels,this.states=e.states,this.user=e.user,this.secrets=e.secrets,this.entities=e.entities}name;version;title;description;icon;readme;configuration;events;actions;channels;states;user;secrets;identifier;entities};var w=require("@botpress/client");var I=class{constructor(e){this.client=e}createConversation=e=>this.client.createConversation(e);getConversation=e=>this.client.getConversation(e);listConversations=e=>this.client.listConversations(e);getOrCreateConversation=e=>this.client.getOrCreateConversation(e);updateConversation=e=>this.client.updateConversation(e);deleteConversation=e=>this.client.deleteConversation(e);listParticipants=e=>this.client.listParticipants(e);addParticipant=e=>this.client.addParticipant(e);getParticipant=e=>this.client.getParticipant(e);removeParticipant=e=>this.client.removeParticipant(e);createEvent=e=>this.client.createEvent(e);getEvent=e=>this.client.getEvent(e);listEvents=e=>this.client.listEvents(e);createMessage=e=>this.client.createMessage(e);getOrCreateMessage=e=>this.client.getOrCreateMessage(e);getMessage=e=>this.client.getMessage(e);updateMessage=e=>this.client.updateMessage(e);listMessages=e=>this.client.listMessages(e);deleteMessage=e=>this.client.deleteMessage(e);createUser=e=>this.client.createUser(e);getUser=e=>this.client.getUser(e);listUsers=e=>this.client.listUsers(e);getOrCreateUser=e=>this.client.getOrCreateUser(e);updateUser=e=>this.client.updateUser(e);deleteUser=e=>this.client.deleteUser(e);getState=e=>this.client.getState(e);setState=e=>this.client.setState(e);getOrSetState=e=>this.client.getOrSetState(e);patchState=e=>this.client.patchState(e);configureIntegration=e=>this.client.configureIntegration(e)};var F=j(require("util")),E=t=>{if(process.env.BP_LOG_FORMAT==="json")return JSON.stringify({msg:F.default.format(...t),visible_to_bot_owner:!0});{let[e,...n]=t;return F.default.format(`[For Bot Owner] ${e}`,...n)}},W={forBot:()=>({info:(...t)=>{console.info(E(t))},warn:(...t)=>{console.warn(E(t))},error:(...t)=>{console.error(E(t))},debug:(...t)=>{console.debug(E(t))}})};var Z=t=>async e=>{let n=$(e.headers),a=new I(new w.Client({botId:n.botId,integrationId:n.integrationId})),s={ctx:n,req:e,client:a,logger:W,instance:t};try{let r;switch(n.operation){case"webhook_received":r=await Be(s);break;case"register":r=await Ce(s);break;case"unregister":r=await xe(s);break;case"message_created":r=await Ee(s);break;case"action_triggered":r=await we(s);break;case"ping":r=await ve(s);break;case"create_user":r=await Se(s);break;case"create_conversation":r=await Pe(s);break;default:throw new Error(`Unknown operation ${n.operation}`)}return r?{...r,status:r.status??200}:{status:200}}catch(r){if(r instanceof w.RuntimeError)return{status:r.code,body:JSON.stringify(r.toJSON())};throw r}},ve=async t=>{},Be=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{let{req:r}=u(n);return s.webhook({client:t,ctx:e,req:r,logger:a})},Ce=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.register)return;let{webhookUrl:r}=u(n);await s.register({client:t,ctx:e,webhookUrl:r,logger:a})},xe=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.unregister)return;let{webhookUrl:r}=u(n);await s.unregister({ctx:e,webhookUrl:r,client:t,logger:a})},Se=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.createUser)return;let{tags:r}=u(n);return await s.createUser({ctx:e,client:t,tags:r,logger:a})},Pe=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.createConversation)return;let{channel:r,tags:i}=u(n);return await s.createConversation({ctx:e,client:t,channel:r,tags:i,logger:a})},Ee=async({ctx:t,req:e,client:n,logger:a,instance:s})=>{let{conversation:r,user:i,type:l,payload:f,message:m}=u(e),G=s.channels[r.channel];if(!G)throw new Error(`Channel ${r.channel} not found`);let L=G.messages[l];if(!L)throw new Error(`Message of type ${l} not found in channel ${r.channel}`);await L({ctx:t,conversation:r,message:m,user:i,type:l,client:n,payload:f,ack:async({tags:Y})=>{await n.updateMessage({id:m.id,tags:Y})},logger:a})},we=async({req:t,ctx:e,client:n,logger:a,instance:s})=>{let{input:r,type:i}=u(t);if(!i)throw new Error("Missing action type");let l=s.actions[i];if(!l)throw new Error(`Action ${i} not found`);let f=await l({ctx:e,input:r,client:n,type:i,logger:a});return{body:JSON.stringify({output:f})}};var M=class{props;actions;channels;register;unregister;createUser;createConversation;webhook;constructor(e){this.props=e,this.actions=e.actions,this.channels=e.channels,this.register=e.register,this.unregister=e.unregister,this.createUser=e.createUser,this.createConversation=e.createConversation,this.webhook=e.handler}handler=Z(this);start=e=>C(this.handler,e)};var Q=j(require("@botpress/client"));var y=class{constructor(e){this.client=e}getConversation=e=>this.client.getConversation(e);listConversations=e=>this.client.listConversations(e);updateConversation=e=>this.client.updateConversation(e);deleteConversation=e=>this.client.deleteConversation(e);listParticipants=e=>this.client.listParticipants(e);addParticipant=e=>this.client.addParticipant(e);getParticipant=e=>this.client.getParticipant(e);removeParticipant=e=>this.client.removeParticipant(e);getEvent=e=>this.client.getEvent(e);listEvents=e=>this.client.listEvents(e);createMessage=e=>this.client.createMessage(e);getOrCreateMessage=e=>this.client.getOrCreateMessage(e);getMessage=e=>this.client.getMessage(e);updateMessage=e=>this.client.updateMessage(e);listMessages=e=>this.client.listMessages(e);deleteMessage=e=>this.client.deleteMessage(e);getUser=e=>this.client.getUser(e);listUsers=e=>this.client.listUsers(e);updateUser=e=>this.client.updateUser(e);deleteUser=e=>this.client.deleteUser(e);getState=e=>this.client.getState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));setState=e=>this.client.setState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));getOrSetState=e=>this.client.getOrSetState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));patchState=e=>this.client.patchState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));callAction=e=>this.client.callAction(e);createConversation=e=>this.client.createConversation(e);getOrCreateConversation=e=>this.client.getOrCreateConversation(e);createUser=e=>this.client.createUser(e);getOrCreateUser=e=>this.client.getOrCreateUser(e)};var J=require("@bpinternal/zui");var Me=J.z.enum(["event_received","register","unregister","ping","action_triggered"]),V=t=>{let e=t[b],n=t[v],a=t[R],s=Me.parse(t[B]);if(!e)throw new Error("Missing bot headers");if(!a)throw new Error("Missing type headers");if(!n)throw new Error("Missing configuration headers");if(!s)throw new Error("Missing operation headers");return{botId:e,operation:s,type:a,configuration:n?JSON.parse(Buffer.from(n,"base64").toString("utf-8")):{}}};var X=t=>async e=>{let n=V(e.headers);n.operation!=="ping"&&h.info(`Received ${n.operation} operation for bot ${n.botId} of type ${n.type}`);let a=new y(new Q.Client({botId:n.botId})),s={req:e,ctx:n,client:a,instance:t};switch(n.operation){case"action_triggered":throw new Error(`Operation ${n.operation} not supported yet`);case"event_received":await De(s);break;case"register":await ke(s);break;case"unregister":await Ae(s);break;case"ping":await Ue(s);break;default:throw new Error(`Unknown operation ${n.operation}`)}return{status:200}},Ue=async t=>{},ke=async t=>{},Ae=async t=>{},De=async({ctx:t,req:e,client:n,instance:a})=>{h.debug(`Received event ${t.type}`);let s=u(e),r=s.event;switch(t.type){case"message_created":let i={user:r.payload.user,conversation:r.payload.conversation,message:r.payload.message,states:r.payload.states,event:r};await Promise.all(a.messageHandlers.map(m=>m({client:n,ctx:t,...i})));break;case"state_expired":let l={state:r.payload.state};await Promise.all(a.stateExpiredHandlers.map(m=>m({client:n,ctx:t,...l})));break;default:let f={event:s.event};await Promise.all(a.eventHandlers.map(m=>m({client:n,ctx:t,...f})))}};var U=class{_state={messageHandlers:[],eventHandlers:[],stateExpiredHandlers:[]};props;constructor(e){this.props=e}message=e=>{this._state.messageHandlers.push(e)};event=e=>{this._state.eventHandlers.push(e)};stateExpired=e=>{this._state.stateExpiredHandlers.push(e)};handler=X(this._state);start=e=>C(this.handler,e)};0&&(module.exports={Bot,BotSpecificClient,Integration,IntegrationDefinition,IntegrationSpecificClient,botIdHeader,botUserIdHeader,configurationHeader,integrationIdHeader,messages,operationHeader,parseBody,serve,studioComponentDefinitions,typeHeader,webhookIdHeader,z});
2
2
  //# sourceMappingURL=index.js.map
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/const.ts", "../src/serve.ts", "../src/log.ts", "../src/integration/context.ts", "../src/integration/definition.ts", "../src/integration/server.ts", "../src/integration/client/index.ts", "../src/integration/logger.ts", "../src/integration/implementation.ts", "../src/bot/server.ts", "../src/bot/client/index.ts", "../src/bot/context.ts", "../src/bot/implementation.ts"],
4
- "sourcesContent": ["export * as messages from './message'\nexport * from './const'\nexport * from './serve'\n\nexport {\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationContext,\n IntegrationSpecificClient,\n} from './integration'\n\nexport { Bot, BotProps, BotContext, BotSpecificClient, IntegrationInstance } from './bot'\n\n/**\n * @deprecated Infer type of integration message handlers instead\n */\nexport type AckFunction = (props: { tags: Record<string, string> }) => Promise<void>\n", "import { z } from 'zod'\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\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} as const // should use satisfies operator but this works for older versions of TS\n", "export const botIdHeader = 'x-bot-id'\nexport const botUserIdHeader = 'x-bot-user-id'\nexport const integrationIdHeader = 'x-integration-id'\nexport const webhookIdHeader = 'x-webhook-id'\n\nexport const configurationHeader = 'x-bp-configuration'\nexport const operationHeader = 'x-bp-operation'\nexport const typeHeader = 'x-bp-type'\n", "import { createServer, IncomingMessage, Server } from 'node:http'\nimport { log } from './log'\n\nexport type Request = {\n body?: string\n path: string\n query: string\n method: string\n headers: { [key: string]: string | undefined }\n}\n\nexport type Response = {\n body?: string\n headers?: { [key: string]: string }\n status?: number\n}\n\nexport type Handler = (req: Request) => Promise<Response | void>\n\nexport function parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n return JSON.parse(req.body)\n}\n\nexport async function serve(\n handler: Handler,\n port: number = 8072,\n callback: (port: number) => void = defaultCallback\n): Promise<Server> {\n /* eslint-disable @typescript-eslint/no-misused-promises */\n const server = createServer(async (req, res) => {\n try {\n const request = await mapIncomingMessageToRequest(req)\n if (request.path === '/health') {\n res.writeHead(200).end('ok')\n return\n }\n const response = await handler(request)\n res.writeHead(response?.status ?? 200, response?.headers ?? {}).end(response?.body ?? '{}')\n } catch (e: any) {\n log.error('Error while handling request', { error: e?.message ?? 'Internal error occured' })\n res.writeHead(500).end(JSON.stringify({ error: e?.message ?? 'Internal error occured' }))\n }\n })\n\n server.listen(port, () => callback(port))\n return server\n}\n\nasync function mapIncomingMessageToRequest(incoming: IncomingMessage): Promise<Request> {\n const body = await readBody(incoming)\n const headers = {} as Request['headers']\n\n for (let i = 0; i < incoming.rawHeaders.length; i += 2) {\n const key = incoming.rawHeaders[i]!.toLowerCase()\n const value = incoming.rawHeaders[i + 1]!\n headers[key] = value\n }\n\n const url = new URL(\n incoming.url ?? '',\n incoming.headers.host ? `http://${incoming.headers.host}` : 'http://botpress.cloud'\n )\n\n return {\n body,\n path: url.pathname,\n query: trimPrefix(url.search, '?'),\n headers,\n method: incoming.method?.toUpperCase() ?? 'GET',\n }\n}\n\nfunction trimPrefix(value: string, prefix: string) {\n return value.indexOf(prefix) === 0 ? value.slice(prefix.length) : value\n}\n\nasync function readBody(incoming: IncomingMessage) {\n return new Promise<string | undefined>((resolve, reject) => {\n if (incoming.method !== 'POST' && incoming.method !== 'PUT' && incoming.method !== 'PATCH') {\n return resolve(undefined)\n }\n\n let body = ''\n\n incoming.on('data', (chunk) => (body += chunk.toString()))\n incoming.on('error', (e) => reject(e))\n incoming.on('end', () => resolve(body))\n })\n}\n\nfunction defaultCallback(port: number) {\n log.info(`Listening on port ${port}`)\n}\n", "export type Logger = {\n debug(message: string, metadata?: any): void\n info(message: string, metadata?: any): void\n warn(message: string, metadata?: any): void\n error(message: string, metadata?: any): void\n}\nexport const log: Logger = console\n", "import { z } from 'zod'\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../const'\n\nexport const integrationOperationSchema = z.enum([\n 'webhook_received',\n 'message_created',\n 'action_triggered',\n 'register',\n 'unregister',\n 'ping',\n 'create_user',\n 'create_conversation',\n])\n\nexport type IntegrationOperation = z.infer<typeof integrationOperationSchema>\n\nexport type IntegrationContext<Configuration = any> = {\n botId: string\n botUserId: string\n integrationId: string\n webhookId: string\n operation: IntegrationOperation\n configuration: Configuration\n}\n\nexport const extractContext = (headers: Record<string, string | undefined>): IntegrationContext => {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\n const base64Configuration = headers[configurationHeader]\n const operation = integrationOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!botUserId) {\n throw new Error('Missing bot user headers')\n }\n\n if (!integrationId) {\n throw new Error('Missing integration headers')\n }\n\n if (!webhookId) {\n throw new Error('Missing webhook headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n botUserId,\n integrationId,\n webhookId,\n operation,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import { SchemaDefinition } from '../schema'\nimport { AnyZodObject } from '../type-utils'\n\ntype BaseConfig = AnyZodObject\ntype BaseEvents = Record<string, AnyZodObject>\ntype BaseActions = Record<string, AnyZodObject>\ntype BaseChannels = Record<string, Record<string, AnyZodObject>>\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEntities = Record<string, AnyZodObject>\n\ntype TagDefinition = {\n title?: string\n description?: string\n}\n\ntype ConfigurationDefinition<TConfig extends BaseConfig> = SchemaDefinition<TConfig> & {\n identifier?: {\n required?: boolean\n linkTemplateScript?: string\n }\n}\n\ntype EventDefinition<TEvent extends BaseEvents[string]> = SchemaDefinition<TEvent> & {\n title?: string\n description?: string\n}\n\ntype ChannelDefinition<TChannel extends BaseChannels[string]> = {\n title?: string\n description?: string\n messages: {\n [K in keyof TChannel]: SchemaDefinition<TChannel[K]>\n }\n message?: {\n tags?: Record<string, TagDefinition>\n }\n conversation?: Partial<{\n tags: Record<string, TagDefinition>\n /**\n * @deprecated\n */\n creation: {\n enabled: boolean\n requiredTags: string[]\n }\n }>\n}\n\ntype ActionDefinition<TAction extends BaseActions[string]> = {\n title?: string\n description?: string\n input: SchemaDefinition<TAction>\n output: SchemaDefinition<AnyZodObject> // cannot infer both input and output types (typescript limitation)\n}\n\ntype StateDefinition<TState extends BaseStates[string]> = SchemaDefinition<TState> & {\n type: 'integration' | 'conversation' | 'user'\n}\n\ntype UserDefinition = Partial<{\n tags: Record<string, TagDefinition>\n /**\n * @deprecated\n */\n creation: {\n enabled: boolean\n requiredTags: string[]\n }\n}>\n\ntype SecretDefinition = {\n optional?: boolean\n description?: string\n}\n\ntype EntityDefinition<TEntity extends BaseEntities[string]> = SchemaDefinition<TEntity> & {\n title?: string\n description?: string\n}\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig = BaseConfig,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> = {\n name: string\n version: string\n\n title?: string\n description?: string\n icon?: string\n readme?: string\n\n identifier?: {\n extractScript?: string\n fallbackHandlerScript?: string\n }\n\n configuration?: ConfigurationDefinition<TConfig>\n events?: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: ChannelDefinition<TChannels[K]>\n }\n\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n\n user?: UserDefinition\n\n secrets?: Record<string, SecretDefinition>\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n}\n\nexport class IntegrationDefinition<\n TConfig extends BaseConfig = BaseConfig,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n public readonly title: this['props']['title']\n public readonly description: this['props']['description']\n public readonly icon: this['props']['icon']\n public readonly readme: this['props']['readme']\n public readonly configuration: this['props']['configuration']\n public readonly events: this['props']['events']\n public readonly actions: this['props']['actions']\n public readonly channels: this['props']['channels']\n public readonly states: this['props']['states']\n public readonly user: this['props']['user']\n public readonly secrets: this['props']['secrets']\n public readonly identifier: this['props']['identifier']\n public readonly entities: this['props']['entities']\n\n public constructor(\n public readonly props: IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>\n ) {\n this.name = props.name\n this.version = props.version\n this.icon = props.icon\n this.readme = props.readme\n this.title = props.title\n this.identifier = props.identifier\n this.description = props.description\n this.configuration = props.configuration\n this.events = props.events\n this.actions = props.actions\n this.channels = props.channels\n this.states = props.states\n this.user = props.user\n this.secrets = props.secrets\n this.entities = props.entities\n }\n}\n", "import { Client, RuntimeError, type Conversation, type Message, type User } from '@botpress/client'\nimport { Request, Response, parseBody } from '../serve'\nimport { Cast, Merge } from '../type-utils'\nimport { IntegrationSpecificClient } from './client'\nimport { ToTags } from './client/types'\nimport { extractContext, type IntegrationContext } from './context'\nimport { BaseIntegration } from './generic'\nimport { IntegrationLogger, integrationLogger } from './logger'\n\ntype PrefixConfig<TIntegration extends BaseIntegration> = { enforcePrefix: TIntegration['name'] }\n\ntype CommonArgs<TIntegration extends BaseIntegration> = {\n ctx: IntegrationContext<TIntegration['configuration']>\n client: IntegrationSpecificClient<TIntegration>\n logger: IntegrationLogger\n}\n\ntype RegisterPayload = { webhookUrl: string }\ntype RegisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & RegisterPayload\n\ntype UnregisterPayload = { webhookUrl: string }\ntype UnregisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & UnregisterPayload\n\ntype WebhookPayload = { req: Request }\ntype WebhookArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & WebhookPayload\n\ntype ActionPayload<T extends string, I> = { type: T; input: I }\ntype ActionArgs<TIntegration extends BaseIntegration, T extends string, I> = CommonArgs<TIntegration> &\n ActionPayload<T, I>\n\ntype CreateUserPayload<TIntegration extends BaseIntegration> = {\n tags: ToTags<keyof TIntegration['user']['tags'], PrefixConfig<TIntegration>>\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'], PrefixConfig<TIntegration>>\n}\ntype CreateConversationArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> &\n CreateConversationPayload<TIntegration>\n\ntype MessagePayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = {\n type: TMessage\n payload: TIntegration['channels'][TChannel]['messages'][TMessage]\n conversation: Merge<\n Conversation,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags'], PrefixConfig<TIntegration>>\n }\n >\n message: Merge<\n Message,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags'], PrefixConfig<TIntegration>>\n }\n >\n user: Merge<\n User,\n {\n tags: ToTags<keyof TIntegration['user']['tags'], PrefixConfig<TIntegration>>\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: {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags'], PrefixConfig<TIntegration>>\n }) => Promise<void>\n }\n\nexport type RegisterFunction<TIntegration extends BaseIntegration> = (\n props: RegisterArgs<TIntegration>\n) => Promise<void>\n\nexport type UnregisterFunction<TIntegration extends BaseIntegration> = (\n props: UnregisterArgs<TIntegration>\n) => Promise<void>\n\nexport type WebhookFunction<TIntegration extends BaseIntegration> = (\n props: WebhookArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ActionFunctions<TIntegration extends BaseIntegration> = {\n [ActionType in keyof TIntegration['actions']]: (\n props: ActionArgs<TIntegration, Cast<ActionType, string>, TIntegration['actions'][ActionType]['input']>\n ) => Promise<TIntegration['actions'][ActionType]['output']>\n}\n\nexport type CreateUserFunction<TIntegration extends BaseIntegration> = (\n props: CreateUserArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type CreateConversationFunction<TIntegration extends BaseIntegration> = (\n props: CreateConversationArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ChannelFunctions<TIntegration extends BaseIntegration> = {\n [ChannelName in keyof TIntegration['channels']]: {\n messages: {\n [MessageType in keyof TIntegration['channels'][ChannelName]['messages']]: (\n props: CommonArgs<TIntegration> & MessageArgs<TIntegration, ChannelName, MessageType>\n ) => Promise<void>\n }\n }\n}\n\nexport type IntegrationHandlers<TIntegration extends BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n webhook: WebhookFunction<TIntegration>\n createUser?: CreateUserFunction<TIntegration>\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\ntype ServerProps<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & {\n req: Request\n instance: IntegrationHandlers<TIntegration>\n}\n\nexport const integrationHandler =\n <TIntegration extends BaseIntegration>(instance: IntegrationHandlers<TIntegration>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n const client = new IntegrationSpecificClient<TIntegration>(\n new Client({ botId: ctx.botId, integrationId: ctx.integrationId })\n )\n\n const props = {\n ctx,\n req,\n client,\n logger: integrationLogger,\n instance,\n }\n\n try {\n let response: Response | void\n switch (ctx.operation) {\n case 'webhook_received':\n response = await onWebhook<TIntegration>(props)\n break\n case 'register':\n response = await onRegister<TIntegration>(props)\n break\n case 'unregister':\n response = await onUnregister<TIntegration>(props)\n break\n case 'message_created':\n response = await onMessageCreated<TIntegration>(props)\n break\n case 'action_triggered':\n response = await onActionTriggered<TIntegration>(props)\n break\n case 'ping':\n response = await onPing<TIntegration>(props)\n break\n case 'create_user':\n response = await onCreateUser<TIntegration>(props)\n break\n case 'create_conversation':\n response = await onCreateConversation<TIntegration>(props)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n return response ? { ...response, status: response.status ?? 200 } : { status: 200 }\n } catch (e) {\n if (e instanceof RuntimeError) {\n return { status: e.code, body: JSON.stringify(e.toJSON()) }\n } else {\n throw e\n }\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 const ack = async ({ tags }: { tags: Record<string, string> }) => {\n await client.updateMessage({\n id: message.id,\n tags: tags as any, // TODO: fix this\n })\n }\n\n await messageHandler({ ctx, conversation, message, user, type, client, payload, ack, logger })\n}\n\nconst onActionTriggered = async <TIntegration extends BaseIntegration>({\n req,\n ctx,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { input, type } = parseBody<ActionPayload<string, any>>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = instance.actions[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const output = await action({ ctx, input, client, type, logger })\n\n return {\n body: JSON.stringify({ output }),\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseIntegration } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the integration's properties.\n */\nexport class IntegrationSpecificClient<TIntegration extends BaseIntegration> {\n public constructor(private readonly client: Client) {}\n\n public createConversation: routes.CreateConversation<TIntegration> = ((x) =>\n this.client.createConversation(x)) as routes.CreateConversation<TIntegration>\n public getConversation: routes.GetConversation<TIntegration> = ((x) =>\n this.client.getConversation(x)) as routes.GetConversation<TIntegration>\n public listConversations: routes.ListConversations<TIntegration> = ((x) =>\n this.client.listConversations(x)) as routes.ListConversations<TIntegration>\n public getOrCreateConversation: routes.GetOrCreateConversation<TIntegration> = ((x) =>\n this.client.getOrCreateConversation(x)) as routes.GetOrCreateConversation<TIntegration>\n public updateConversation: routes.UpdateConversation<TIntegration> = ((x) =>\n this.client.updateConversation(x)) as routes.UpdateConversation<TIntegration>\n public deleteConversation: routes.DeleteConversation<TIntegration> = ((x) =>\n this.client.deleteConversation(x)) as routes.DeleteConversation<TIntegration>\n\n public listParticipants: routes.ListParticipants<TIntegration> = ((x) =>\n this.client.listParticipants(x)) as routes.ListParticipants<TIntegration>\n public addParticipant: routes.AddParticipant<TIntegration> = ((x) =>\n this.client.addParticipant(x)) as routes.AddParticipant<TIntegration>\n public getParticipant: routes.GetParticipant<TIntegration> = ((x) =>\n this.client.getParticipant(x)) as routes.GetParticipant<TIntegration>\n public removeParticipant: routes.RemoveParticipant<TIntegration> = ((x) =>\n this.client.removeParticipant(x)) as routes.RemoveParticipant<TIntegration>\n\n public createEvent: routes.CreateEvent<TIntegration> = ((x) =>\n this.client.createEvent(x)) as routes.CreateEvent<TIntegration>\n public getEvent: routes.GetEvent<TIntegration> = ((x) => this.client.getEvent(x)) as routes.GetEvent<TIntegration>\n public listEvents: routes.ListEvents<TIntegration> = ((x) =>\n this.client.listEvents(x)) as routes.ListEvents<TIntegration>\n\n public createMessage: routes.CreateMessage<TIntegration> = ((x) =>\n this.client.createMessage(x)) as routes.CreateMessage<TIntegration>\n public getOrCreateMessage: routes.GetOrCreateMessage<TIntegration> = ((x) =>\n this.client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TIntegration>\n public getMessage: routes.GetMessage<TIntegration> = ((x) =>\n this.client.getMessage(x)) as routes.GetMessage<TIntegration>\n public updateMessage: routes.UpdateMessage<TIntegration> = ((x) =>\n this.client.updateMessage(x)) as routes.UpdateMessage<TIntegration>\n public listMessages: routes.ListMessages<TIntegration> = ((x) =>\n this.client.listMessages(x)) as routes.ListMessages<TIntegration>\n public deleteMessage: routes.DeleteMessage<TIntegration> = ((x) =>\n this.client.deleteMessage(x)) as routes.DeleteMessage<TIntegration>\n\n public createUser: routes.CreateUser<TIntegration> = ((x) =>\n this.client.createUser(x)) as routes.CreateUser<TIntegration>\n public getUser: routes.GetUser<TIntegration> = ((x) => this.client.getUser(x)) as routes.GetUser<TIntegration>\n public listUsers: routes.ListUsers<TIntegration> = (x) => this.client.listUsers(x)\n public getOrCreateUser: routes.GetOrCreateUser<TIntegration> = ((x) =>\n this.client.getOrCreateUser(x)) as routes.GetOrCreateUser<TIntegration>\n public updateUser: routes.UpdateUser<TIntegration> = ((x) =>\n this.client.updateUser(x)) as routes.UpdateUser<TIntegration>\n public deleteUser: routes.DeleteUser<TIntegration> = (x) => this.client.deleteUser(x)\n\n public getState: routes.GetState<TIntegration> = ((x) => this.client.getState(x)) as routes.GetState<TIntegration>\n public setState: routes.SetState<TIntegration> = ((x) => this.client.setState(x)) as routes.SetState<TIntegration>\n public getOrSetState: routes.GetOrSetState<TIntegration> = ((x) =>\n this.client.getOrSetState(x)) as routes.GetOrSetState<TIntegration>\n public patchState: routes.PatchState<TIntegration> = ((x) =>\n this.client.patchState(x)) as routes.PatchState<TIntegration>\n\n public configureIntegration: routes.ConfigureIntegration<TIntegration> = (x) => this.client.configureIntegration(x)\n}\n", "/* eslint-disable no-console */\nimport util from 'util'\n\nconst serializeForBotMessage = (args: Parameters<typeof util.format>) => {\n if (process.env['BP_LOG_FORMAT'] === 'json') {\n return JSON.stringify({ msg: util.format(...args), visible_to_bot_owner: true })\n } else {\n const [format, ...param] = args\n return util.format(`[For Bot Owner] ${format}`, ...param)\n }\n}\n\nexport const integrationLogger = {\n /**\n * Use this function to log messages that will be displayed to the Bot Owner.\n */\n forBot: () => {\n return {\n info: (...args: Parameters<typeof console.info>) => {\n console.info(serializeForBotMessage(args))\n },\n warn: (...args: Parameters<typeof console.warn>) => {\n console.warn(serializeForBotMessage(args))\n },\n error: (...args: Parameters<typeof console.error>) => {\n console.error(serializeForBotMessage(args))\n },\n debug: (...args: Parameters<typeof console.debug>) => {\n console.debug(serializeForBotMessage(args))\n },\n }\n },\n}\n\nexport type IntegrationLogger = typeof integrationLogger\n", "import type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport { BaseIntegration } from './generic'\nimport {\n RegisterFunction,\n UnregisterFunction,\n WebhookFunction,\n CreateUserFunction,\n CreateConversationFunction,\n ActionFunctions,\n ChannelFunctions,\n integrationHandler,\n} from './server'\n\nexport type IntegrationImplementationProps<TIntegration extends BaseIntegration = BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n handler: WebhookFunction<TIntegration>\n /**\n * @deprecated\n */\n createUser?: CreateUserFunction<TIntegration>\n /**\n * @deprecated\n */\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\nexport class IntegrationImplementation<TIntegration extends BaseIntegration = BaseIntegration> {\n public readonly props: IntegrationImplementationProps<TIntegration>\n public readonly actions: IntegrationImplementationProps<TIntegration>['actions']\n public readonly channels: IntegrationImplementationProps<TIntegration>['channels']\n public readonly register: IntegrationImplementationProps<TIntegration>['register']\n public readonly unregister: IntegrationImplementationProps<TIntegration>['unregister']\n public readonly createUser: IntegrationImplementationProps<TIntegration>['createUser']\n public readonly createConversation: IntegrationImplementationProps<TIntegration>['createConversation']\n public readonly webhook: IntegrationImplementationProps<TIntegration>['handler']\n\n public constructor(props: IntegrationImplementationProps<TIntegration>) {\n this.props = props\n this.actions = props.actions\n this.channels = props.channels\n this.register = props.register\n this.unregister = props.unregister\n this.createUser = props.createUser\n this.createConversation = props.createConversation\n this.webhook = props.handler\n }\n\n public readonly handler = integrationHandler<TIntegration>(this)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import * as client from '@botpress/client'\nimport { log } from '../log'\nimport { Request, Response, parseBody } from '../serve'\nimport { BotSpecificClient } from './client'\nimport * as types from './client/types'\nimport { BotContext, extractContext } from './context'\nimport { BaseBot } from './generic'\n\ntype CommonArgs<TBot extends BaseBot> = {\n ctx: BotContext\n client: BotSpecificClient<TBot>\n}\n\ntype MessagePayload<TBot extends BaseBot> = {\n user: client.User\n conversation: client.Conversation\n message: types.MessageResponse<TBot>['message']\n event: client.Event\n states: {\n [TState in keyof TBot['states']]: {\n type: StateType\n payload: TBot['states'][TState]\n }\n }\n}\ntype MessageArgs<TBot extends BaseBot> = CommonArgs<TBot> & MessagePayload<TBot>\n\ntype EventPayload<TBot extends BaseBot> = types.EventResponse<TBot>\ntype EventArgs<TBot extends BaseBot> = CommonArgs<TBot> & EventPayload<TBot>\n\ntype StateExpiredPayload = { state: client.State }\ntype StateExpiredArgs<TBot extends BaseBot> = CommonArgs<TBot> & StateExpiredPayload\n\nexport type StateType = 'conversation' | 'user' | 'bot'\n\nexport type MessageHandler<TBot extends BaseBot> = (args: MessageArgs<TBot>) => Promise<void>\n\nexport type EventHandler<TBot extends BaseBot> = (args: EventArgs<TBot>) => Promise<void>\n\nexport type StateExpiredHandler<TBot extends BaseBot> = (args: StateExpiredArgs<TBot>) => Promise<void>\n\nexport type BotHandlers<TBot extends BaseBot> = {\n messageHandlers: MessageHandler<TBot>[]\n eventHandlers: EventHandler<TBot>[]\n stateExpiredHandlers: StateExpiredHandler<TBot>[]\n}\n\ntype ServerProps<TBot extends BaseBot> = CommonArgs<TBot> & {\n req: Request\n instance: BotHandlers<TBot>\n}\n\nexport const botHandler =\n <TBot extends BaseBot>(instance: BotHandlers<TBot>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n if (ctx.operation !== 'ping') {\n log.info(`Received ${ctx.operation} operation for bot ${ctx.botId} of type ${ctx.type}`)\n }\n\n const botClient = new BotSpecificClient<TBot>(new client.Client({ botId: ctx.botId }))\n\n const props: ServerProps<TBot> = {\n req,\n ctx,\n client: botClient,\n instance,\n }\n\n switch (ctx.operation) {\n case 'action_triggered':\n throw new Error(`Operation ${ctx.operation} not supported yet`)\n case 'event_received':\n await onEventReceived<TBot>(props as ServerProps<TBot>)\n break\n case 'register':\n await onRegister<TBot>(props as ServerProps<TBot>)\n break\n case 'unregister':\n await onUnregister<TBot>(props as ServerProps<TBot>)\n break\n case 'ping':\n await onPing<TBot>(props as ServerProps<TBot>)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n\n return { status: 200 }\n }\n\nconst onPing = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onRegister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onUnregister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onEventReceived = async <TBot extends BaseBot>({ ctx, req, client, instance }: ServerProps<TBot>) => {\n log.debug(`Received event ${ctx.type}`)\n\n const body = parseBody<EventPayload<TBot>>(req)\n const event = body.event as client.Event\n\n switch (ctx.type) {\n case 'message_created':\n const messagePayload: MessagePayload<TBot> = {\n user: event.payload.user,\n conversation: event.payload.conversation,\n message: event.payload.message,\n states: event.payload.states,\n event,\n }\n\n await Promise.all(\n instance.messageHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...messagePayload,\n })\n )\n )\n break\n case 'state_expired':\n const statePayload: StateExpiredPayload = { state: event.payload.state }\n await Promise.all(\n instance.stateExpiredHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...statePayload,\n })\n )\n )\n break\n default:\n const eventPayload = { event: body.event } as EventPayload<TBot>\n await Promise.all(\n instance.eventHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...eventPayload,\n })\n )\n )\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseBot } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the bot's properties.\n */\nexport class BotSpecificClient<TBot extends BaseBot> {\n public constructor(private readonly client: Client) {}\n\n public getConversation: routes.GetConversation<TBot> = (x) => this.client.getConversation(x)\n public listConversations: routes.ListConversations<TBot> = (x) => this.client.listConversations(x)\n public updateConversation: routes.UpdateConversation<TBot> = (x) => this.client.updateConversation(x)\n public deleteConversation: routes.DeleteConversation<TBot> = (x) => this.client.deleteConversation(x)\n\n public listParticipants: routes.ListParticipants<TBot> = (x) => this.client.listParticipants(x)\n public addParticipant: routes.AddParticipant<TBot> = (x) => this.client.addParticipant(x)\n public getParticipant: routes.GetParticipant<TBot> = (x) => this.client.getParticipant(x)\n public removeParticipant: routes.RemoveParticipant<TBot> = (x) => this.client.removeParticipant(x)\n\n public getEvent: routes.GetEvent<TBot> = ((x) => this.client.getEvent(x)) as routes.GetEvent<TBot>\n public listEvents: routes.ListEvents<TBot> = ((x) => this.client.listEvents(x)) as routes.ListEvents<TBot>\n\n public createMessage: routes.CreateMessage<TBot> = ((x) => this.client.createMessage(x)) as routes.CreateMessage<TBot>\n public getOrCreateMessage: routes.GetOrCreateMessage<TBot> = ((x) =>\n this.client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TBot>\n public getMessage: routes.GetMessage<TBot> = ((x) => this.client.getMessage(x)) as routes.GetMessage<TBot>\n public updateMessage: routes.UpdateMessage<TBot> = ((x) => this.client.updateMessage(x)) as routes.UpdateMessage<TBot>\n public listMessages: routes.ListMessages<TBot> = ((x) => this.client.listMessages(x)) as routes.ListMessages<TBot>\n public deleteMessage: routes.DeleteMessage<TBot> = ((x) => this.client.deleteMessage(x)) as routes.DeleteMessage<TBot>\n\n public getUser: routes.GetUser<TBot> = (x) => this.client.getUser(x)\n public listUsers: routes.ListUsers<TBot> = (x) => this.client.listUsers(x)\n public updateUser: routes.UpdateUser<TBot> = (x) => this.client.updateUser(x)\n public deleteUser: routes.DeleteUser<TBot> = (x) => this.client.deleteUser(x)\n\n public getState: routes.GetState<TBot> = ((x) =>\n this.client.getState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetState<TBot>\n public setState: routes.SetState<TBot> = ((x) =>\n this.client.setState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.SetState<TBot>\n public getOrSetState: routes.GetOrSetState<TBot> = ((x) =>\n this.client\n .getOrSetState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetOrSetState<TBot>\n public patchState: routes.PatchState<TBot> = ((x) =>\n this.client\n .patchState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.PatchState<TBot>\n\n public callAction: routes.CallAction<TBot> = (x) => this.client.callAction(x)\n\n /**\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 'zod'\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 { z } from 'zod'\nimport { SchemaDefinition } from '../schema'\nimport { serve } from '../serve'\nimport { AnyZodObject, Cast } from '../type-utils'\nimport { BaseIntegrations } from './generic'\nimport { IntegrationInstance } from './integration-instance'\nimport { botHandler, MessageHandler, EventHandler, StateExpiredHandler, StateType } from './server'\n\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEvents = Record<string, AnyZodObject>\n\ntype TagDefinition = {\n title?: string\n description?: string\n}\n\ntype StateDefinition<TState extends BaseStates[string]> = SchemaDefinition<TState> & {\n type: StateType\n expiry?: number\n}\n\ntype RecurringEventDefinition<TEvents extends BaseEvents> = {\n [K in keyof TEvents]: {\n type: K\n payload: z.infer<TEvents[K]>\n schedule: { cron: string }\n }\n}[keyof TEvents]\n\ntype EventDefinition<TEvent extends BaseEvents[string]> = SchemaDefinition<TEvent>\n\ntype ConfigurationDefinition = SchemaDefinition\n\ntype UserDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype ConversationDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype MessageDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type BotProps<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n integrations?: {\n [K in keyof TIntegrations]?: IntegrationInstance<Cast<K, string>>\n }\n user?: UserDefinition\n conversation?: ConversationDefinition // TODO: add configuration to generic and infer from there\n message?: MessageDefinition\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n configuration?: ConfigurationDefinition\n events?: {\n [K in keyof TEvents]: EventDefinition<TEvents[K]>\n }\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n}\n\ntype BotFrom<TIntegrations extends BaseIntegrations, TStates extends BaseStates, TEvents extends BaseEvents> = {\n integrations: TIntegrations\n states: {\n [K in keyof TStates]: z.infer<TStates[K]>\n }\n events: {\n [K in keyof TEvents]: z.infer<TEvents[K]>\n }\n}\n\ntype BotState<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n messageHandlers: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n eventHandlers: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n stateExpiredHandlers: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n}\n\nexport class Bot<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> {\n private _state: BotState<TIntegrations, TStates, TEvents> = {\n messageHandlers: [],\n eventHandlers: [],\n stateExpiredHandlers: [],\n }\n\n public readonly props: BotProps<TIntegrations, TStates, TEvents>\n\n public constructor(props: BotProps<TIntegrations, TStates, TEvents>) {\n this.props = props\n }\n\n public readonly message = (handler: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.messageHandlers.push(handler)\n }\n public readonly event = (handler: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.eventHandlers.push(handler)\n }\n public readonly stateExpired = (handler: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.stateExpiredHandlers.push(handler)\n }\n\n public readonly handler = botHandler(this._state)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n"],
5
- "mappings": "2jBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,SAAAE,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,8BAAAC,EAAA,gBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,wBAAAC,EAAA,aAAAC,EAAA,oBAAAC,EAAA,cAAAC,EAAA,UAAAC,EAAA,eAAAC,EAAA,oBAAAC,IAAA,eAAAC,GAAAjB,ICAA,IAAAkB,EAAA,GAAAC,EAAAD,EAAA,cAAAE,KAAA,IAAAC,EAAkB,eAEZC,EAAiB,IAAE,OAAO,EAAE,IAAI,CAAC,EAEjCC,GAAoB,IAAE,OAAO,CACjC,KAAMD,CACR,CAAC,EAEKE,GAAwB,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,GAAwB,IAAE,OAAO,CACrC,SAAU,IAAE,OAAO,EACnB,UAAW,IAAE,OAAO,EACp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KAAK,OAAO,gBAAgB,KAAKA,CAAO,CAC1C,EACgB,MAASA,GAA0E,CACjG,KAAK,OAAO,cAAc,KAAKA,CAAO,CACxC,EACgB,aAAgBA,GAAiF,CAC/G,KAAK,OAAO,qBAAqB,KAAKA,CAAO,CAC/C,EAEgB,QAAUC,EAAW,KAAK,MAAM,EAChC,MAASC,GAAmCC,EAAM,KAAK,QAASD,CAAI,CACtF",
6
- "names": ["src_exports", "__export", "Bot", "BotSpecificClient", "IntegrationImplementation", "IntegrationDefinition", "IntegrationSpecificClient", "botIdHeader", "botUserIdHeader", "configurationHeader", "integrationIdHeader", "message_exports", "operationHeader", "parseBody", "serve", "typeHeader", "webhookIdHeader", "__toCommonJS", "message_exports", "__export", "defaults", "import_zod", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "botIdHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationHeader", "operationHeader", "typeHeader", "import_node_http", "log", "parseBody", "req", "serve", "handler", "port", "callback", "defaultCallback", "server", "res", "request", "mapIncomingMessageToRequest", "response", "e", "log", "incoming", "body", "readBody", "headers", "i", "key", "value", "url", "trimPrefix", "prefix", "resolve", "reject", "chunk", "import_zod", "integrationOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "botUserId", "botUserIdHeader", "integrationId", "integrationIdHeader", "webhookId", "webhookIdHeader", "base64Configuration", "configurationHeader", "operation", "operationHeader", "IntegrationDefinition", "props", "import_client", "IntegrationSpecificClient", "client", "x", "import_util", "serializeForBotMessage", "args", "util", "format", "param", "integrationLogger", "integrationHandler", "instance", "req", "ctx", "extractContext", "client", "IntegrationSpecificClient", "props", "integrationLogger", "response", "onWebhook", "onRegister", "onUnregister", "onMessageCreated", "onActionTriggered", "onPing", "onCreateUser", "onCreateConversation", "e", "_", "incomingRequest", "logger", "parseBody", "webhookUrl", "tags", "channel", "conversation", "user", "type", "payload", "message", "channelHandler", "messageHandler", "input", "action", "output", "IntegrationImplementation", "props", "integrationHandler", "port", "serve", "client", "BotSpecificClient", "client", "x", "y", "import_zod", "botOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "base64Configuration", "configurationHeader", "type", "typeHeader", "operation", "operationHeader", "botHandler", "instance", "req", "ctx", "extractContext", "log", "botClient", "BotSpecificClient", "props", "onEventReceived", "onRegister", "onUnregister", "onPing", "_", "client", "body", "parseBody", "event", "messagePayload", "handler", "statePayload", "eventPayload", "Bot", "props", "handler", "botHandler", "port", "serve"]
3
+ "sources": ["../src/index.ts", "../src/message.ts", "../src/zui.ts", "../src/const.ts", "../src/serve.ts", "../src/log.ts", "../src/integration/context.ts", "../src/integration/definition.ts", "../src/integration/server.ts", "../src/integration/client/index.ts", "../src/integration/logger.ts", "../src/integration/implementation.ts", "../src/bot/server.ts", "../src/bot/client/index.ts", "../src/bot/context.ts", "../src/bot/implementation.ts"],
4
+ "sourcesContent": ["export * as messages from './message'\nexport * from './const'\nexport * from './serve'\nexport * from './zui'\n\nexport {\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationContext,\n IntegrationSpecificClient,\n} from './integration'\n\nexport { Bot, BotProps, BotContext, BotSpecificClient, IntegrationInstance } from './bot'\n", "import { z } from './zui'\n\nconst NonEmptyString = z.string().min(1)\n\nconst textMessageSchema = z.object({\n text: NonEmptyString,\n})\n\nconst markdownMessageSchema = z.object({\n markdown: NonEmptyString,\n})\n\nconst imageMessageSchema = z.object({\n imageUrl: NonEmptyString,\n})\n\nconst audioMessageSchema = z.object({\n audioUrl: NonEmptyString,\n})\n\nconst videoMessageSchema = z.object({\n videoUrl: NonEmptyString,\n})\n\nconst fileMessageSchema = z.object({\n fileUrl: NonEmptyString,\n title: NonEmptyString.optional(),\n})\n\nconst locationMessageSchema = z.object({\n latitude: z.number(),\n longitude: z.number(),\n address: z.string().optional(),\n title: z.string().optional(),\n})\n\nconst cardSchema = z.object({\n title: NonEmptyString,\n subtitle: NonEmptyString.optional(),\n imageUrl: NonEmptyString.optional(),\n actions: z.array(\n z.object({\n action: z.enum(['postback', 'url', 'say']),\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst choiceSchema = z.object({\n text: NonEmptyString,\n options: z.array(\n z.object({\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst carouselSchema = z.object({\n items: z.array(cardSchema),\n})\n\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} as const // should use satisfies operator but this works for older versions of TS\n", "import { z, type UIComponentDefinitions, type DefaultComponentDefinitions } from '@bpinternal/zui'\nexport * from '@bpinternal/zui'\n\nconst commonInputParams = z.object({\n allowDynamicVariable: z.boolean().optional(),\n horizontal: z.boolean().optional(),\n})\n\nexport const studioComponentDefinitions = {\n string: {\n textInput: {\n id: 'textInput',\n params: commonInputParams.extend({\n multiLine: z.boolean().optional(),\n growVertically: z.boolean().optional(),\n suggestions: z.array(z.string()).optional(),\n }),\n },\n dropdown: {\n id: 'dropdown',\n params: commonInputParams.extend({\n filterable: z.boolean().optional(),\n }),\n },\n radiogroup: {\n id: 'radiogroup',\n params: commonInputParams.extend({}),\n },\n datepicker: {\n id: 'datepicker',\n params: commonInputParams.extend({\n dateFormat: z.string().optional(),\n minDate: z.string().optional(),\n maxDate: z.string().optional(),\n defaultTimezone: z.string().optional(),\n disableTimezoneSelection: z.boolean().optional(),\n highlightCurrentDay: z.boolean().optional(),\n showShortcutButtons: z.boolean().optional(),\n showOutsideDaysOfMonth: z.boolean().optional(),\n firstDayOfWeek: z.number().optional(),\n canChangeMonth: z.boolean().optional(),\n showWeekNumbers: z.boolean().optional(),\n }),\n },\n timepicker: {\n id: 'timepicker',\n params: commonInputParams.extend({\n useAMPM: z.boolean().optional(),\n timeFormat: z.string().optional(),\n minTime: z.string().optional(),\n maxTime: z.string().optional(),\n showArrowButtons: z.boolean().optional(),\n precision: z.enum(['minute', 'second', 'millisecond']).optional(),\n }),\n },\n variablepicker: {\n id: 'variablepicker',\n params: z.object({\n type: z.enum([\n 'any',\n 'string',\n 'number',\n 'boolean',\n 'object',\n 'pattern',\n 'date',\n 'array',\n 'target',\n 'time',\n 'enum',\n ]),\n horizontal: z.boolean().optional(),\n }),\n },\n richTextEditor: {\n id: 'richTextEditor',\n params: z.object({\n allowDynamicVariable: z.boolean().optional(),\n resizable: z.boolean().optional(),\n }),\n },\n JSONInput: {\n id: 'JSONInput',\n params: commonInputParams.extend({\n showPreview: z.boolean().optional(),\n showValidationError: z.boolean().optional(),\n }),\n },\n fileInput: {\n id: 'fileInput',\n params: commonInputParams.extend({\n fileTypes: z.array(z.enum(['image', 'audio', 'video'])).optional(),\n showUploadedFiles: z.boolean().optional(),\n }),\n },\n },\n number: {\n numberInput: {\n id: 'numberInput',\n params: commonInputParams.extend({\n allowNumericCharactersOnly: z.boolean().optional(),\n stepSize: z.number().optional(),\n }),\n },\n slider: {\n id: 'slider',\n params: z.object({\n horizontal: z.boolean().optional(),\n stepSize: z.number().optional(),\n }),\n },\n },\n boolean: {\n switch: {\n id: 'switch',\n params: commonInputParams,\n },\n },\n array: {\n optionList: {\n id: 'optionList',\n params: commonInputParams,\n },\n stringList: {\n id: 'stringList',\n params: commonInputParams,\n },\n },\n object: {\n collapsible: {\n id: 'collapsible',\n params: z.object({\n defaultOpen: z.boolean().optional(),\n }),\n },\n },\n} as const satisfies UIComponentDefinitions\n\nexport type UI<Namespace extends 'studio' | 'dashboard' = 'studio'> = Namespace extends 'studio'\n ? typeof studioComponentDefinitions\n : Namespace extends 'dashboard'\n ? DefaultComponentDefinitions\n : any\n\nexport default z\nexport { z }\n", "export const botIdHeader = 'x-bot-id'\nexport const botUserIdHeader = 'x-bot-user-id'\nexport const integrationIdHeader = 'x-integration-id'\nexport const webhookIdHeader = 'x-webhook-id'\n\nexport const configurationHeader = 'x-bp-configuration'\nexport const operationHeader = 'x-bp-operation'\nexport const typeHeader = 'x-bp-type'\n", "import { createServer, IncomingMessage, Server } from 'node:http'\nimport { log } from './log'\n\nexport type Request = {\n body?: string\n path: string\n query: string\n method: string\n headers: { [key: string]: string | undefined }\n}\n\nexport type Response = {\n body?: string\n headers?: { [key: string]: string }\n status?: number\n}\n\nexport type Handler = (req: Request) => Promise<Response | void>\n\nexport function parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n return JSON.parse(req.body)\n}\n\nexport async function serve(\n handler: Handler,\n port: number = 8072,\n callback: (port: number) => void = defaultCallback\n): Promise<Server> {\n /* eslint-disable @typescript-eslint/no-misused-promises */\n const server = createServer(async (req, res) => {\n try {\n const request = await mapIncomingMessageToRequest(req)\n if (request.path === '/health') {\n res.writeHead(200).end('ok')\n return\n }\n const response = await handler(request)\n res.writeHead(response?.status ?? 200, response?.headers ?? {}).end(response?.body ?? '{}')\n } catch (e: any) {\n log.error('Error while handling request', { error: e?.message ?? 'Internal error occured' })\n res.writeHead(500).end(JSON.stringify({ error: e?.message ?? 'Internal error occured' }))\n }\n })\n\n server.listen(port, () => callback(port))\n return server\n}\n\nasync function mapIncomingMessageToRequest(incoming: IncomingMessage): Promise<Request> {\n const body = await readBody(incoming)\n const headers = {} as Request['headers']\n\n for (let i = 0; i < incoming.rawHeaders.length; i += 2) {\n const key = incoming.rawHeaders[i]!.toLowerCase()\n const value = incoming.rawHeaders[i + 1]!\n headers[key] = value\n }\n\n const url = new URL(\n incoming.url ?? '',\n incoming.headers.host ? `http://${incoming.headers.host}` : 'http://botpress.cloud'\n )\n\n return {\n body,\n path: url.pathname,\n query: trimPrefix(url.search, '?'),\n headers,\n method: incoming.method?.toUpperCase() ?? 'GET',\n }\n}\n\nfunction trimPrefix(value: string, prefix: string) {\n return value.indexOf(prefix) === 0 ? value.slice(prefix.length) : value\n}\n\nasync function readBody(incoming: IncomingMessage) {\n return new Promise<string | undefined>((resolve, reject) => {\n if (incoming.method !== 'POST' && incoming.method !== 'PUT' && incoming.method !== 'PATCH') {\n return resolve(undefined)\n }\n\n let body = ''\n\n incoming.on('data', (chunk) => (body += chunk.toString()))\n incoming.on('error', (e) => reject(e))\n incoming.on('end', () => resolve(body))\n })\n}\n\nfunction defaultCallback(port: number) {\n log.info(`Listening on port ${port}`)\n}\n", "export type Logger = {\n debug(message: string, metadata?: any): void\n info(message: string, metadata?: any): void\n warn(message: string, metadata?: any): void\n error(message: string, metadata?: any): void\n}\nexport const log: Logger = console\n", "import { z } from '@bpinternal/zui'\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../const'\n\nexport const integrationOperationSchema = z.enum([\n 'webhook_received',\n 'message_created',\n 'action_triggered',\n 'register',\n 'unregister',\n 'ping',\n 'create_user',\n 'create_conversation',\n])\n\nexport type IntegrationOperation = z.infer<typeof integrationOperationSchema>\n\nexport type IntegrationContext<Configuration = any> = {\n botId: string\n botUserId: string\n integrationId: string\n webhookId: string\n operation: IntegrationOperation\n configuration: Configuration\n}\n\nexport const extractContext = (headers: Record<string, string | undefined>): IntegrationContext => {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\n const base64Configuration = headers[configurationHeader]\n const operation = integrationOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!botUserId) {\n throw new Error('Missing bot user headers')\n }\n\n if (!integrationId) {\n throw new Error('Missing integration headers')\n }\n\n if (!webhookId) {\n throw new Error('Missing webhook headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n botUserId,\n integrationId,\n webhookId,\n operation,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import { SchemaDefinition } from '../schema'\nimport { AnyZodObject } from '../type-utils'\n\ntype BaseConfig = AnyZodObject\ntype BaseEvents = Record<string, AnyZodObject>\ntype BaseActions = Record<string, AnyZodObject>\ntype BaseChannels = Record<string, Record<string, AnyZodObject>>\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEntities = Record<string, AnyZodObject>\n\ntype TagDefinition = {\n title?: string\n description?: string\n}\n\ntype ConfigurationDefinition<TConfig extends BaseConfig> = SchemaDefinition<TConfig> & {\n identifier?: {\n required?: boolean\n linkTemplateScript?: string\n }\n}\n\ntype EventDefinition<TEvent extends BaseEvents[string]> = SchemaDefinition<TEvent> & {\n title?: string\n description?: string\n}\n\ntype ChannelDefinition<TChannel extends BaseChannels[string]> = {\n title?: string\n description?: string\n messages: {\n [K in keyof TChannel]: SchemaDefinition<TChannel[K]>\n }\n message?: {\n tags?: Record<string, TagDefinition>\n }\n conversation?: Partial<{\n tags: Record<string, TagDefinition>\n /**\n * @deprecated\n */\n creation: {\n enabled: boolean\n requiredTags: string[]\n }\n }>\n}\n\ntype ActionDefinition<TAction extends BaseActions[string]> = {\n title?: string\n description?: string\n input: SchemaDefinition<TAction>\n output: SchemaDefinition<AnyZodObject> // cannot infer both input and output types (typescript limitation)\n}\n\ntype StateDefinition<TState extends BaseStates[string]> = SchemaDefinition<TState> & {\n type: 'integration' | 'conversation' | 'user'\n}\n\ntype UserDefinition = Partial<{\n tags: Record<string, TagDefinition>\n /**\n * @deprecated\n */\n creation: {\n enabled: boolean\n requiredTags: string[]\n }\n}>\n\ntype SecretDefinition = {\n optional?: boolean\n description?: string\n}\n\ntype EntityDefinition<TEntity extends BaseEntities[string]> = SchemaDefinition<TEntity> & {\n title?: string\n description?: string\n}\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig = BaseConfig,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> = {\n name: string\n version: string\n\n title?: string\n description?: string\n icon?: string\n readme?: string\n\n identifier?: {\n extractScript?: string\n fallbackHandlerScript?: string\n }\n\n configuration?: ConfigurationDefinition<TConfig>\n events?: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: ChannelDefinition<TChannels[K]>\n }\n\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n\n user?: UserDefinition\n\n secrets?: Record<string, SecretDefinition>\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n}\n\nexport class IntegrationDefinition<\n TConfig extends BaseConfig = BaseConfig,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n public readonly title: this['props']['title']\n public readonly description: this['props']['description']\n public readonly icon: this['props']['icon']\n public readonly readme: this['props']['readme']\n public readonly configuration: this['props']['configuration']\n public readonly events: this['props']['events']\n public readonly actions: this['props']['actions']\n public readonly channels: this['props']['channels']\n public readonly states: this['props']['states']\n public readonly user: this['props']['user']\n public readonly secrets: this['props']['secrets']\n public readonly identifier: this['props']['identifier']\n public readonly entities: this['props']['entities']\n\n public constructor(\n public readonly props: IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>\n ) {\n this.name = props.name\n this.version = props.version\n this.icon = props.icon\n this.readme = props.readme\n this.title = props.title\n this.identifier = props.identifier\n this.description = props.description\n this.configuration = props.configuration\n this.events = props.events\n this.actions = props.actions\n this.channels = props.channels\n this.states = props.states\n this.user = props.user\n this.secrets = props.secrets\n this.entities = props.entities\n }\n}\n", "import { Client, RuntimeError, type Conversation, type Message, type User } from '@botpress/client'\nimport { Request, Response, parseBody } from '../serve'\nimport { Cast, Merge } from '../type-utils'\nimport { IntegrationSpecificClient } from './client'\nimport { ToTags } from './client/types'\nimport { extractContext, type IntegrationContext } from './context'\nimport { BaseIntegration } from './generic'\nimport { IntegrationLogger, integrationLogger } from './logger'\n\ntype CommonArgs<TIntegration extends BaseIntegration> = {\n ctx: IntegrationContext<TIntegration['configuration']>\n client: IntegrationSpecificClient<TIntegration>\n logger: IntegrationLogger\n}\n\ntype RegisterPayload = { webhookUrl: string }\ntype RegisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & RegisterPayload\n\ntype UnregisterPayload = { webhookUrl: string }\ntype UnregisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & UnregisterPayload\n\ntype WebhookPayload = { req: Request }\ntype WebhookArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & WebhookPayload\n\ntype ActionPayload<T extends string, I> = { type: T; input: I }\ntype ActionArgs<TIntegration extends BaseIntegration, T extends string, I> = CommonArgs<TIntegration> &\n ActionPayload<T, I>\n\ntype CreateUserPayload<TIntegration extends BaseIntegration> = {\n tags: ToTags<keyof TIntegration['user']['tags']>\n}\n\ntype CreateUserArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & CreateUserPayload<TIntegration>\n\ntype CreateConversationPayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'] = keyof TIntegration['channels']\n> = {\n channel: TChannel\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n}\n\ntype CreateConversationArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> &\n CreateConversationPayload<TIntegration>\n\ntype MessagePayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = {\n type: TMessage\n payload: TIntegration['channels'][TChannel]['messages'][TMessage]\n conversation: Merge<\n Conversation,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n }\n >\n message: Merge<\n Message,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']>\n }\n >\n user: Merge<\n User,\n {\n tags: ToTags<keyof TIntegration['user']['tags']>\n }\n >\n}\n\ntype MessageArgs<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = CommonArgs<TIntegration> &\n MessagePayload<TIntegration, TChannel, TMessage> & {\n ack: (props: { tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']> }) => Promise<void>\n }\n\nexport type RegisterFunction<TIntegration extends BaseIntegration> = (\n props: RegisterArgs<TIntegration>\n) => Promise<void>\n\nexport type UnregisterFunction<TIntegration extends BaseIntegration> = (\n props: UnregisterArgs<TIntegration>\n) => Promise<void>\n\nexport type WebhookFunction<TIntegration extends BaseIntegration> = (\n props: WebhookArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ActionFunctions<TIntegration extends BaseIntegration> = {\n [ActionType in keyof TIntegration['actions']]: (\n props: ActionArgs<TIntegration, Cast<ActionType, string>, TIntegration['actions'][ActionType]['input']>\n ) => Promise<TIntegration['actions'][ActionType]['output']>\n}\n\nexport type CreateUserFunction<TIntegration extends BaseIntegration> = (\n props: CreateUserArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type CreateConversationFunction<TIntegration extends BaseIntegration> = (\n props: CreateConversationArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ChannelFunctions<TIntegration extends BaseIntegration> = {\n [ChannelName in keyof TIntegration['channels']]: {\n messages: {\n [MessageType in keyof TIntegration['channels'][ChannelName]['messages']]: (\n props: CommonArgs<TIntegration> & MessageArgs<TIntegration, ChannelName, MessageType>\n ) => Promise<void>\n }\n }\n}\n\nexport type IntegrationHandlers<TIntegration extends BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n webhook: WebhookFunction<TIntegration>\n createUser?: CreateUserFunction<TIntegration>\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\ntype ServerProps<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & {\n req: Request\n instance: IntegrationHandlers<TIntegration>\n}\n\nexport const integrationHandler =\n <TIntegration extends BaseIntegration>(instance: IntegrationHandlers<TIntegration>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n const client = new IntegrationSpecificClient<TIntegration>(\n new Client({ botId: ctx.botId, integrationId: ctx.integrationId })\n )\n\n const props = {\n ctx,\n req,\n client,\n logger: integrationLogger,\n instance,\n }\n\n try {\n let response: Response | void\n switch (ctx.operation) {\n case 'webhook_received':\n response = await onWebhook<TIntegration>(props)\n break\n case 'register':\n response = await onRegister<TIntegration>(props)\n break\n case 'unregister':\n response = await onUnregister<TIntegration>(props)\n break\n case 'message_created':\n response = await onMessageCreated<TIntegration>(props)\n break\n case 'action_triggered':\n response = await onActionTriggered<TIntegration>(props)\n break\n case 'ping':\n response = await onPing<TIntegration>(props)\n break\n case 'create_user':\n response = await onCreateUser<TIntegration>(props)\n break\n case 'create_conversation':\n response = await onCreateConversation<TIntegration>(props)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n return response ? { ...response, status: response.status ?? 200 } : { status: 200 }\n } catch (e) {\n if (e instanceof RuntimeError) {\n return { status: e.code, body: JSON.stringify(e.toJSON()) }\n } else {\n throw e\n }\n }\n }\n\nconst onPing = async <TIntegration extends BaseIntegration>(_: ServerProps<TIntegration>) => {}\n\nconst onWebhook = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req: incomingRequest,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { req } = parseBody<WebhookPayload>(incomingRequest)\n return instance.webhook({ client, ctx, req, logger })\n}\n\nconst onRegister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.register) {\n return\n }\n const { webhookUrl } = parseBody<RegisterPayload>(req)\n await instance.register({ client, ctx, webhookUrl, logger })\n}\n\nconst onUnregister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.unregister) {\n return\n }\n const { webhookUrl } = parseBody<UnregisterPayload>(req)\n await instance.unregister({ ctx, webhookUrl, client, logger })\n}\n\nconst onCreateUser = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createUser) {\n return\n }\n const { tags } = parseBody<CreateUserPayload<TIntegration>>(req)\n return await instance.createUser({ ctx, client, tags, logger })\n}\n\nconst onCreateConversation = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createConversation) {\n return\n }\n const { channel, tags } = parseBody<CreateConversationPayload<TIntegration>>(req)\n return await instance.createConversation({ ctx, client, channel, tags, logger })\n}\n\nconst onMessageCreated = async <TIntegration extends BaseIntegration>({\n ctx,\n req,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { conversation, user, type, payload, message } = parseBody<MessagePayload<TIntegration, string, string>>(req)\n\n const channelHandler = instance.channels[conversation.channel]\n\n if (!channelHandler) {\n throw new Error(`Channel ${conversation.channel} not found`)\n }\n\n const messageHandler = channelHandler.messages[type]\n\n if (!messageHandler) {\n throw new Error(`Message of type ${type} not found in channel ${conversation.channel}`)\n }\n\n type UpdateMessageProps = Parameters<(typeof client)['updateMessage']>[0]\n const ack = async ({ tags }: Pick<UpdateMessageProps, 'tags'>) => {\n await client.updateMessage({\n id: message.id,\n tags,\n })\n }\n\n await messageHandler({ ctx, conversation, message, user, type, client, payload, ack, logger })\n}\n\nconst onActionTriggered = async <TIntegration extends BaseIntegration>({\n req,\n ctx,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { input, type } = parseBody<ActionPayload<string, any>>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = instance.actions[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const output = await action({ ctx, input, client, type, logger })\n\n return {\n body: JSON.stringify({ output }),\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseIntegration } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the integration's properties.\n */\nexport class IntegrationSpecificClient<TIntegration extends BaseIntegration> {\n public constructor(private readonly client: Client) {}\n\n public createConversation: routes.CreateConversation<TIntegration> = ((x) =>\n this.client.createConversation(x)) as routes.CreateConversation<TIntegration>\n public getConversation: routes.GetConversation<TIntegration> = ((x) =>\n this.client.getConversation(x)) as routes.GetConversation<TIntegration>\n public listConversations: routes.ListConversations<TIntegration> = ((x) =>\n this.client.listConversations(x)) as routes.ListConversations<TIntegration>\n public getOrCreateConversation: routes.GetOrCreateConversation<TIntegration> = ((x) =>\n this.client.getOrCreateConversation(x)) as routes.GetOrCreateConversation<TIntegration>\n public updateConversation: routes.UpdateConversation<TIntegration> = ((x) =>\n this.client.updateConversation(x)) as routes.UpdateConversation<TIntegration>\n public deleteConversation: routes.DeleteConversation<TIntegration> = ((x) =>\n this.client.deleteConversation(x)) as routes.DeleteConversation<TIntegration>\n\n public listParticipants: routes.ListParticipants<TIntegration> = ((x) =>\n this.client.listParticipants(x)) as routes.ListParticipants<TIntegration>\n public addParticipant: routes.AddParticipant<TIntegration> = ((x) =>\n this.client.addParticipant(x)) as routes.AddParticipant<TIntegration>\n public getParticipant: routes.GetParticipant<TIntegration> = ((x) =>\n this.client.getParticipant(x)) as routes.GetParticipant<TIntegration>\n public removeParticipant: routes.RemoveParticipant<TIntegration> = ((x) =>\n this.client.removeParticipant(x)) as routes.RemoveParticipant<TIntegration>\n\n public createEvent: routes.CreateEvent<TIntegration> = ((x) =>\n this.client.createEvent(x)) as routes.CreateEvent<TIntegration>\n public getEvent: routes.GetEvent<TIntegration> = ((x) => this.client.getEvent(x)) as routes.GetEvent<TIntegration>\n public listEvents: routes.ListEvents<TIntegration> = ((x) =>\n this.client.listEvents(x)) as routes.ListEvents<TIntegration>\n\n public createMessage: routes.CreateMessage<TIntegration> = ((x) =>\n this.client.createMessage(x)) as routes.CreateMessage<TIntegration>\n public getOrCreateMessage: routes.GetOrCreateMessage<TIntegration> = ((x) =>\n this.client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TIntegration>\n public getMessage: routes.GetMessage<TIntegration> = ((x) =>\n this.client.getMessage(x)) as routes.GetMessage<TIntegration>\n public updateMessage: routes.UpdateMessage<TIntegration> = ((x) =>\n this.client.updateMessage(x)) as routes.UpdateMessage<TIntegration>\n public listMessages: routes.ListMessages<TIntegration> = ((x) =>\n this.client.listMessages(x)) as routes.ListMessages<TIntegration>\n public deleteMessage: routes.DeleteMessage<TIntegration> = ((x) =>\n this.client.deleteMessage(x)) as routes.DeleteMessage<TIntegration>\n\n public createUser: routes.CreateUser<TIntegration> = ((x) =>\n this.client.createUser(x)) as routes.CreateUser<TIntegration>\n public getUser: routes.GetUser<TIntegration> = ((x) => this.client.getUser(x)) as routes.GetUser<TIntegration>\n public listUsers: routes.ListUsers<TIntegration> = (x) => this.client.listUsers(x)\n public getOrCreateUser: routes.GetOrCreateUser<TIntegration> = ((x) =>\n this.client.getOrCreateUser(x)) as routes.GetOrCreateUser<TIntegration>\n public updateUser: routes.UpdateUser<TIntegration> = ((x) =>\n this.client.updateUser(x)) as routes.UpdateUser<TIntegration>\n public deleteUser: routes.DeleteUser<TIntegration> = (x) => this.client.deleteUser(x)\n\n public getState: routes.GetState<TIntegration> = ((x) => this.client.getState(x)) as routes.GetState<TIntegration>\n public setState: routes.SetState<TIntegration> = ((x) => this.client.setState(x)) as routes.SetState<TIntegration>\n public getOrSetState: routes.GetOrSetState<TIntegration> = ((x) =>\n this.client.getOrSetState(x)) as routes.GetOrSetState<TIntegration>\n public patchState: routes.PatchState<TIntegration> = ((x) =>\n this.client.patchState(x)) as routes.PatchState<TIntegration>\n\n public configureIntegration: routes.ConfigureIntegration<TIntegration> = (x) => this.client.configureIntegration(x)\n}\n", "/* eslint-disable no-console */\nimport util from 'util'\n\nconst serializeForBotMessage = (args: Parameters<typeof util.format>) => {\n if (process.env['BP_LOG_FORMAT'] === 'json') {\n return JSON.stringify({ msg: util.format(...args), visible_to_bot_owner: true })\n } else {\n const [format, ...param] = args\n return util.format(`[For Bot Owner] ${format}`, ...param)\n }\n}\n\nexport const integrationLogger = {\n /**\n * Use this function to log messages that will be displayed to the Bot Owner.\n */\n forBot: () => {\n return {\n info: (...args: Parameters<typeof console.info>) => {\n console.info(serializeForBotMessage(args))\n },\n warn: (...args: Parameters<typeof console.warn>) => {\n console.warn(serializeForBotMessage(args))\n },\n error: (...args: Parameters<typeof console.error>) => {\n console.error(serializeForBotMessage(args))\n },\n debug: (...args: Parameters<typeof console.debug>) => {\n console.debug(serializeForBotMessage(args))\n },\n }\n },\n}\n\nexport type IntegrationLogger = typeof integrationLogger\n", "import type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport { BaseIntegration } from './generic'\nimport {\n RegisterFunction,\n UnregisterFunction,\n WebhookFunction,\n CreateUserFunction,\n CreateConversationFunction,\n ActionFunctions,\n ChannelFunctions,\n integrationHandler,\n} from './server'\n\nexport type IntegrationImplementationProps<TIntegration extends BaseIntegration = BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n handler: WebhookFunction<TIntegration>\n /**\n * @deprecated\n */\n createUser?: CreateUserFunction<TIntegration>\n /**\n * @deprecated\n */\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\nexport class IntegrationImplementation<TIntegration extends BaseIntegration = BaseIntegration> {\n public readonly props: IntegrationImplementationProps<TIntegration>\n public readonly actions: IntegrationImplementationProps<TIntegration>['actions']\n public readonly channels: IntegrationImplementationProps<TIntegration>['channels']\n public readonly register: IntegrationImplementationProps<TIntegration>['register']\n public readonly unregister: IntegrationImplementationProps<TIntegration>['unregister']\n public readonly createUser: IntegrationImplementationProps<TIntegration>['createUser']\n public readonly createConversation: IntegrationImplementationProps<TIntegration>['createConversation']\n public readonly webhook: IntegrationImplementationProps<TIntegration>['handler']\n\n public constructor(props: IntegrationImplementationProps<TIntegration>) {\n this.props = props\n this.actions = props.actions\n this.channels = props.channels\n this.register = props.register\n this.unregister = props.unregister\n this.createUser = props.createUser\n this.createConversation = props.createConversation\n this.webhook = props.handler\n }\n\n public readonly handler = integrationHandler<TIntegration>(this)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import * as client from '@botpress/client'\nimport { log } from '../log'\nimport { Request, Response, parseBody } from '../serve'\nimport { BotSpecificClient } from './client'\nimport * as types from './client/types'\nimport { BotContext, extractContext } from './context'\nimport { BaseBot } from './generic'\n\ntype CommonArgs<TBot extends BaseBot> = {\n ctx: BotContext\n client: BotSpecificClient<TBot>\n}\n\ntype MessagePayload<TBot extends BaseBot> = {\n user: client.User\n conversation: client.Conversation\n message: types.MessageResponse<TBot>['message']\n event: client.Event\n states: {\n [TState in keyof TBot['states']]: {\n type: StateType\n payload: TBot['states'][TState]\n }\n }\n}\ntype MessageArgs<TBot extends BaseBot> = CommonArgs<TBot> & MessagePayload<TBot>\n\ntype EventPayload<TBot extends BaseBot> = types.EventResponse<TBot>\ntype EventArgs<TBot extends BaseBot> = CommonArgs<TBot> & EventPayload<TBot>\n\ntype StateExpiredPayload = { state: client.State }\ntype StateExpiredArgs<TBot extends BaseBot> = CommonArgs<TBot> & StateExpiredPayload\n\nexport type StateType = 'conversation' | 'user' | 'bot'\n\nexport type MessageHandler<TBot extends BaseBot> = (args: MessageArgs<TBot>) => Promise<void>\n\nexport type EventHandler<TBot extends BaseBot> = (args: EventArgs<TBot>) => Promise<void>\n\nexport type StateExpiredHandler<TBot extends BaseBot> = (args: StateExpiredArgs<TBot>) => Promise<void>\n\nexport type BotHandlers<TBot extends BaseBot> = {\n messageHandlers: MessageHandler<TBot>[]\n eventHandlers: EventHandler<TBot>[]\n stateExpiredHandlers: StateExpiredHandler<TBot>[]\n}\n\ntype ServerProps<TBot extends BaseBot> = CommonArgs<TBot> & {\n req: Request\n instance: BotHandlers<TBot>\n}\n\nexport const botHandler =\n <TBot extends BaseBot>(instance: BotHandlers<TBot>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n if (ctx.operation !== 'ping') {\n log.info(`Received ${ctx.operation} operation for bot ${ctx.botId} of type ${ctx.type}`)\n }\n\n const botClient = new BotSpecificClient<TBot>(new client.Client({ botId: ctx.botId }))\n\n const props: ServerProps<TBot> = {\n req,\n ctx,\n client: botClient,\n instance,\n }\n\n switch (ctx.operation) {\n case 'action_triggered':\n throw new Error(`Operation ${ctx.operation} not supported yet`)\n case 'event_received':\n await onEventReceived<TBot>(props as ServerProps<TBot>)\n break\n case 'register':\n await onRegister<TBot>(props as ServerProps<TBot>)\n break\n case 'unregister':\n await onUnregister<TBot>(props as ServerProps<TBot>)\n break\n case 'ping':\n await onPing<TBot>(props as ServerProps<TBot>)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n\n return { status: 200 }\n }\n\nconst onPing = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onRegister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onUnregister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onEventReceived = async <TBot extends BaseBot>({ ctx, req, client, instance }: ServerProps<TBot>) => {\n log.debug(`Received event ${ctx.type}`)\n\n const body = parseBody<EventPayload<TBot>>(req)\n const event = body.event as client.Event\n\n switch (ctx.type) {\n case 'message_created':\n const messagePayload: MessagePayload<TBot> = {\n user: event.payload.user,\n conversation: event.payload.conversation,\n message: event.payload.message,\n states: event.payload.states,\n event,\n }\n\n await Promise.all(\n instance.messageHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...messagePayload,\n })\n )\n )\n break\n case 'state_expired':\n const statePayload: StateExpiredPayload = { state: event.payload.state }\n await Promise.all(\n instance.stateExpiredHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...statePayload,\n })\n )\n )\n break\n default:\n const eventPayload = { event: body.event } as EventPayload<TBot>\n await Promise.all(\n instance.eventHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...eventPayload,\n })\n )\n )\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseBot } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the bot's properties.\n */\nexport class BotSpecificClient<TBot extends BaseBot> {\n public constructor(private readonly client: Client) {}\n\n public getConversation: routes.GetConversation<TBot> = (x) => this.client.getConversation(x)\n public listConversations: routes.ListConversations<TBot> = (x) => this.client.listConversations(x)\n public updateConversation: routes.UpdateConversation<TBot> = (x) => this.client.updateConversation(x)\n public deleteConversation: routes.DeleteConversation<TBot> = (x) => this.client.deleteConversation(x)\n\n public listParticipants: routes.ListParticipants<TBot> = (x) => this.client.listParticipants(x)\n public addParticipant: routes.AddParticipant<TBot> = (x) => this.client.addParticipant(x)\n public getParticipant: routes.GetParticipant<TBot> = (x) => this.client.getParticipant(x)\n public removeParticipant: routes.RemoveParticipant<TBot> = (x) => this.client.removeParticipant(x)\n\n public getEvent: routes.GetEvent<TBot> = ((x) => this.client.getEvent(x)) as routes.GetEvent<TBot>\n public listEvents: routes.ListEvents<TBot> = ((x) => this.client.listEvents(x)) as routes.ListEvents<TBot>\n\n public createMessage: routes.CreateMessage<TBot> = ((x) => this.client.createMessage(x)) as routes.CreateMessage<TBot>\n public getOrCreateMessage: routes.GetOrCreateMessage<TBot> = ((x) =>\n this.client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TBot>\n public getMessage: routes.GetMessage<TBot> = ((x) => this.client.getMessage(x)) as routes.GetMessage<TBot>\n public updateMessage: routes.UpdateMessage<TBot> = ((x) => this.client.updateMessage(x)) as routes.UpdateMessage<TBot>\n public listMessages: routes.ListMessages<TBot> = ((x) => this.client.listMessages(x)) as routes.ListMessages<TBot>\n public deleteMessage: routes.DeleteMessage<TBot> = ((x) => this.client.deleteMessage(x)) as routes.DeleteMessage<TBot>\n\n public getUser: routes.GetUser<TBot> = (x) => this.client.getUser(x)\n public listUsers: routes.ListUsers<TBot> = (x) => this.client.listUsers(x)\n public updateUser: routes.UpdateUser<TBot> = (x) => this.client.updateUser(x)\n public deleteUser: routes.DeleteUser<TBot> = (x) => this.client.deleteUser(x)\n\n public getState: routes.GetState<TBot> = ((x) =>\n this.client.getState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetState<TBot>\n public setState: routes.SetState<TBot> = ((x) =>\n this.client.setState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.SetState<TBot>\n public getOrSetState: routes.GetOrSetState<TBot> = ((x) =>\n this.client\n .getOrSetState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetOrSetState<TBot>\n public patchState: routes.PatchState<TBot> = ((x) =>\n this.client\n .patchState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.PatchState<TBot>\n\n public callAction: routes.CallAction<TBot> = (x) => this.client.callAction(x)\n\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public createConversation: routes.CreateConversation<TBot> = (x) => this.client.createConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public getOrCreateConversation: routes.GetOrCreateConversation<TBot> = (x) => this.client.getOrCreateConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public createUser: routes.CreateUser<TBot> = (x) => this.client.createUser(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public getOrCreateUser: routes.GetOrCreateUser<TBot> = (x) => this.client.getOrCreateUser(x)\n}\n", "import { z } from '@bpinternal/zui'\nimport { botIdHeader, configurationHeader, operationHeader, typeHeader } from '../const'\n\nexport const botOperationSchema = z.enum(['event_received', 'register', 'unregister', 'ping', 'action_triggered'])\n\nexport type BotOperation = z.infer<typeof botOperationSchema>\n\nexport type BotContext = {\n botId: string\n type: string\n operation: BotOperation\n configuration: {\n payload: string\n }\n}\n\nexport const extractContext = (headers: Record<string, string | undefined>): BotContext => {\n const botId = headers[botIdHeader]\n const base64Configuration = headers[configurationHeader]\n const type = headers[typeHeader]\n const operation = botOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!type) {\n throw new Error('Missing type headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n operation,\n type,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import { z } from '@bpinternal/zui'\nimport type { Server } from 'node:http'\nimport { SchemaDefinition } from '../schema'\nimport { serve } from '../serve'\nimport { AnyZodObject, Cast } from '../type-utils'\nimport { BaseIntegrations } from './generic'\nimport { IntegrationInstance } from './integration-instance'\nimport { botHandler, MessageHandler, EventHandler, StateExpiredHandler, StateType } from './server'\n\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEvents = Record<string, AnyZodObject>\n\ntype TagDefinition = {\n title?: string\n description?: string\n}\n\ntype StateDefinition<TState extends BaseStates[string]> = SchemaDefinition<TState> & {\n type: StateType\n expiry?: number\n}\n\ntype RecurringEventDefinition<TEvents extends BaseEvents> = {\n [K in keyof TEvents]: {\n type: K\n payload: z.infer<TEvents[K]>\n schedule: { cron: string }\n }\n}[keyof TEvents]\n\ntype EventDefinition<TEvent extends BaseEvents[string]> = SchemaDefinition<TEvent>\n\ntype ConfigurationDefinition = SchemaDefinition\n\ntype UserDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype ConversationDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype MessageDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type BotProps<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n integrations?: {\n [K in keyof TIntegrations]?: IntegrationInstance<Cast<K, string>>\n }\n user?: UserDefinition\n conversation?: ConversationDefinition // TODO: add configuration to generic and infer from there\n message?: MessageDefinition\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n configuration?: ConfigurationDefinition\n events?: {\n [K in keyof TEvents]: EventDefinition<TEvents[K]>\n }\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n}\n\ntype BotFrom<TIntegrations extends BaseIntegrations, TStates extends BaseStates, TEvents extends BaseEvents> = {\n integrations: TIntegrations\n states: {\n [K in keyof TStates]: z.infer<TStates[K]>\n }\n events: {\n [K in keyof TEvents]: z.infer<TEvents[K]>\n }\n}\n\ntype BotState<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n messageHandlers: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n eventHandlers: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n stateExpiredHandlers: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n}\n\nexport class Bot<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> {\n private _state: BotState<TIntegrations, TStates, TEvents> = {\n messageHandlers: [],\n eventHandlers: [],\n stateExpiredHandlers: [],\n }\n\n public readonly props: BotProps<TIntegrations, TStates, TEvents>\n\n public constructor(props: BotProps<TIntegrations, TStates, TEvents>) {\n this.props = props\n }\n\n public readonly message = (handler: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.messageHandlers.push(handler)\n }\n public readonly event = (handler: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.eventHandlers.push(handler)\n }\n public readonly stateExpired = (handler: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.stateExpiredHandlers.push(handler)\n }\n\n public readonly handler = botHandler(this._state)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n"],
5
+ "mappings": "mnBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,SAAAE,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,8BAAAC,EAAA,gBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,wBAAAC,EAAA,aAAAC,EAAA,oBAAAC,EAAA,cAAAC,EAAA,UAAAC,EAAA,+BAAAC,EAAA,eAAAC,EAAA,oBAAAC,EAAA,2BAAAC,GAAAlB,GCAA,IAAAmB,EAAA,GAAAC,EAAAD,EAAA,cAAAE,KCAA,IAAAC,EAAA,GAAAC,EAAAD,EAAA,aAAAE,GAAA,+BAAAC,EAAA,gBAAAC,EAAiF,2BACjFC,EAAAL,EAAc,4BAEd,IAAMM,EAAoB,IAAE,OAAO,CACjC,qBAAsB,IAAE,QAAQ,EAAE,SAAS,EAC3C,WAAY,IAAE,QAAQ,EAAE,SAAS,CACnC,CAAC,EAEYH,EAA6B,CACxC,OAAQ,CACN,UAAW,CACT,GAAI,YACJ,OAAQG,EAAkB,OAAO,CAC/B,UAAW,IAAE,QAAQ,EAAE,SAAS,EAChC,eAAgB,IAAE,QAAQ,EAAE,SAAS,EACrC,YAAa,IAAE,MAAM,IAAE,OAAO,CAAC,EAAE,SAAS,CAC5C,CAAC,CACH,EACA,SAAU,CACR,GAAI,WACJ,OAAQA,EAAkB,OAAO,CAC/B,WAAY,IAAE,QAAQ,EAAE,SAAS,CACnC,CAAC,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IAAMC,EAAN,KAIL,CACQ,OAAoD,CAC1D,gBAAiB,CAAC,EAClB,cAAe,CAAC,EAChB,qBAAsB,CAAC,CACzB,EAEgB,MAET,YAAYC,EAAkD,CACnE,KAAK,MAAQA,CACf,CAEgB,QAAWC,GAA4E,CACrG,KAAK,OAAO,gBAAgB,KAAKA,CAAO,CAC1C,EACgB,MAASA,GAA0E,CACjG,KAAK,OAAO,cAAc,KAAKA,CAAO,CACxC,EACgB,aAAgBA,GAAiF,CAC/G,KAAK,OAAO,qBAAqB,KAAKA,CAAO,CAC/C,EAEgB,QAAUC,EAAW,KAAK,MAAM,EAChC,MAASC,GAAmCC,EAAM,KAAK,QAASD,CAAI,CACtF",
6
+ "names": ["src_exports", "__export", "Bot", "BotSpecificClient", "IntegrationImplementation", "IntegrationDefinition", "IntegrationSpecificClient", "botIdHeader", "botUserIdHeader", "configurationHeader", "integrationIdHeader", "message_exports", "operationHeader", "parseBody", "serve", "studioComponentDefinitions", "typeHeader", "webhookIdHeader", "__toCommonJS", "message_exports", "__export", "defaults", "zui_exports", "__export", "zui_default", "studioComponentDefinitions", "import_zui", "__reExport", "commonInputParams", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "defaults", "botIdHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationHeader", "operationHeader", "typeHeader", "import_node_http", "log", "parseBody", "req", "serve", "handler", "port", "callback", "defaultCallback", "server", "res", "request", "mapIncomingMessageToRequest", "response", "e", "log", "incoming", "body", "readBody", "headers", "i", "key", "value", "url", "trimPrefix", "prefix", "resolve", "reject", "chunk", "__reExport", "src_exports", "zui_exports", "import_zui", "integrationOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "botUserId", "botUserIdHeader", "integrationId", "integrationIdHeader", "webhookId", "webhookIdHeader", "base64Configuration", "configurationHeader", "operation", "operationHeader", "IntegrationDefinition", "props", "import_client", "IntegrationSpecificClient", "client", "x", "import_util", "serializeForBotMessage", "args", "util", "format", "param", "integrationLogger", "integrationHandler", "instance", "req", "ctx", "extractContext", "client", "IntegrationSpecificClient", "props", "integrationLogger", "response", "onWebhook", "onRegister", "onUnregister", "onMessageCreated", "onActionTriggered", "onPing", "onCreateUser", "onCreateConversation", "e", "_", "incomingRequest", "logger", "parseBody", "webhookUrl", "tags", "channel", "conversation", "user", "type", "payload", "message", "channelHandler", "messageHandler", "input", "action", "output", "IntegrationImplementation", "props", "integrationHandler", "port", "serve", "client", "BotSpecificClient", "client", "x", "y", "import_zui", "botOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "base64Configuration", "configurationHeader", "type", "typeHeader", "operation", "operationHeader", "botHandler", "instance", "req", "ctx", "extractContext", "log", "botClient", "BotSpecificClient", "props", "onEventReceived", "onRegister", "onUnregister", "onPing", "_", "client", "body", "parseBody", "event", "messagePayload", "handler", "statePayload", "eventPayload", "Bot", "props", "handler", "botHandler", "port", "serve"]
7
7
  }
@@ -4,29 +4,26 @@ import { BaseIntegration } from '../generic';
4
4
  import { GetChannelByName, ToTags, WithPrefix } from './types';
5
5
  type Arg<F extends (...args: any[]) => any> = Parameters<F>[number];
6
6
  type Res<F extends (...args: any[]) => any> = ReturnType<F>;
7
- type PrefixConfig<TIntegration extends BaseIntegration> = {
8
- allowPrefix: TIntegration['name'];
9
- };
10
7
  type AllChannels<TIntegration extends BaseIntegration> = ValueOf<TIntegration['channels']>;
11
8
  type ConversationResponse<TIntegration extends BaseIntegration, ChannelName extends keyof TIntegration['channels'] = keyof TIntegration['channels']> = {
12
9
  conversation: Merge<Awaited<Res<Client['getConversation']>>['conversation'], {
13
- tags: ToTags<keyof TIntegration['channels'][ChannelName]['conversation']['tags'], PrefixConfig<TIntegration>>;
10
+ tags: ToTags<keyof TIntegration['channels'][ChannelName]['conversation']['tags']>;
14
11
  }>;
15
12
  };
16
13
  export type CreateConversation<TIntegration extends BaseIntegration> = <ChannelName extends keyof TIntegration['channels']>(x: {
17
14
  channel: Cast<ChannelName, string>;
18
- tags: ToTags<keyof GetChannelByName<TIntegration, ChannelName>['conversation']['tags'], PrefixConfig<TIntegration>>;
15
+ tags: ToTags<keyof GetChannelByName<TIntegration, ChannelName>['conversation']['tags']>;
19
16
  }) => Promise<ConversationResponse<TIntegration, ChannelName>>;
20
17
  export type GetConversation<TIntegration extends BaseIntegration> = (x: Arg<Client['getConversation']>) => Promise<ConversationResponse<TIntegration>>;
21
18
  export type ListConversations<TIntegration extends BaseIntegration> = (x: Merge<Arg<Client['listConversations']>, {
22
- tags?: ToTags<keyof AllChannels<TIntegration>['conversation']['tags'], PrefixConfig<TIntegration>>;
19
+ tags?: ToTags<keyof AllChannels<TIntegration>['conversation']['tags']>;
23
20
  }>) => Res<Client['listConversations']>;
24
21
  export type GetOrCreateConversation<TIntegration extends BaseIntegration> = <ChannelName extends keyof TIntegration['channels']>(x: {
25
22
  channel: Cast<ChannelName, string>;
26
- tags: ToTags<keyof GetChannelByName<TIntegration, ChannelName>['conversation']['tags'], PrefixConfig<TIntegration>>;
23
+ tags: ToTags<keyof GetChannelByName<TIntegration, ChannelName>['conversation']['tags']>;
27
24
  }) => Promise<ConversationResponse<TIntegration, ChannelName>>;
28
25
  export type UpdateConversation<TIntegration extends BaseIntegration> = (x: Merge<Arg<Client['updateConversation']>, {
29
- tags: ToTags<keyof AllChannels<TIntegration>['conversation']['tags'], PrefixConfig<TIntegration>>;
26
+ tags: ToTags<keyof AllChannels<TIntegration>['conversation']['tags']>;
30
27
  }>) => Promise<ConversationResponse<TIntegration>>;
31
28
  export type DeleteConversation<_TIntegration extends BaseIntegration> = Client['deleteConversation'];
32
29
  export type ListParticipants<_TIntegration extends BaseIntegration> = Client['listParticipants'];
@@ -56,44 +53,44 @@ export type ListEvents<TIntegration extends BaseIntegration> = (x: Merge<Arg<Cli
56
53
  type MessageResponse<TIntegration extends BaseIntegration, TChannel extends keyof TIntegration['channels'], TMessage extends keyof TIntegration['channels'][TChannel]['messages']> = {
57
54
  message: Merge<Awaited<Res<Client['createMessage']>>['message'], {
58
55
  payload: TIntegration['channels'][TChannel]['messages'][TMessage];
59
- tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags'], PrefixConfig<TIntegration>>;
56
+ tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']>;
60
57
  }>;
61
58
  };
62
59
  export type CreateMessage<TIntegration extends BaseIntegration> = <TChannel extends keyof TIntegration['channels'], TMessage extends keyof TIntegration['channels'][TChannel]['messages']>(x: Merge<Arg<Client['createMessage']>, {
63
60
  type: Cast<TMessage, string>;
64
61
  payload: TIntegration['channels'][TChannel]['messages'][TMessage];
65
- tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags'], PrefixConfig<TIntegration>>;
62
+ tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']>;
66
63
  }>) => Promise<MessageResponse<TIntegration, TChannel, TMessage>>;
67
64
  export type GetOrCreateMessage<TIntegration extends BaseIntegration> = <TChannel extends keyof TIntegration['channels'], TMessage extends keyof TIntegration['channels'][TChannel]['messages']>(x: Merge<Arg<Client['getOrCreateMessage']>, {
68
65
  type: Cast<TMessage, string>;
69
66
  payload: TIntegration['channels'][TChannel]['messages'][TMessage];
70
- tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags'], PrefixConfig<TIntegration>>;
67
+ tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']>;
71
68
  }>) => Promise<MessageResponse<TIntegration, TChannel, TMessage>>;
72
69
  export type GetMessage<TIntegration extends BaseIntegration> = (x: Arg<Client['getMessage']>) => Promise<MessageResponse<TIntegration, keyof TIntegration['channels'], keyof ValueOf<TIntegration['channels']>['messages']>>;
73
70
  export type UpdateMessage<TIntegration extends BaseIntegration> = (x: Merge<Arg<Client['updateMessage']>, {
74
- tags: ToTags<keyof AllChannels<TIntegration>['message']['tags'], PrefixConfig<TIntegration>>;
71
+ tags: ToTags<keyof AllChannels<TIntegration>['message']['tags']>;
75
72
  }>) => Promise<MessageResponse<TIntegration, keyof TIntegration['channels'], keyof ValueOf<TIntegration['channels']>['messages']>>;
76
73
  export type ListMessages<TIntegration extends BaseIntegration> = (x: Merge<Arg<Client['listMessages']>, {
77
- tags: ToTags<keyof AllChannels<TIntegration>['message']['tags'], PrefixConfig<TIntegration>>;
74
+ tags: ToTags<keyof AllChannels<TIntegration>['message']['tags']>;
78
75
  }>) => Res<Client['listMessages']>;
79
76
  export type DeleteMessage<_TIntegration extends BaseIntegration> = Client['deleteMessage'];
80
77
  type UserResponse<TIntegration extends BaseIntegration> = {
81
78
  user: Merge<Awaited<Res<Client['getUser']>>['user'], {
82
- tags: ToTags<keyof TIntegration['user']['tags'], PrefixConfig<TIntegration>>;
79
+ tags: ToTags<keyof TIntegration['user']['tags']>;
83
80
  }>;
84
81
  };
85
82
  export type CreateUser<TIntegration extends BaseIntegration> = (x: Merge<Arg<Client['createUser']>, {
86
- tags: ToTags<keyof TIntegration['user']['tags'], PrefixConfig<TIntegration>>;
83
+ tags: ToTags<keyof TIntegration['user']['tags']>;
87
84
  }>) => Promise<UserResponse<TIntegration>>;
88
85
  export type GetUser<TIntegration extends BaseIntegration> = (x: Arg<Client['getUser']>) => Promise<UserResponse<TIntegration>>;
89
86
  export type ListUsers<TIntegration extends BaseIntegration> = (x: Merge<Arg<Client['listUsers']>, {
90
- tags: ToTags<keyof TIntegration['user']['tags'], PrefixConfig<TIntegration>>;
87
+ tags: ToTags<keyof TIntegration['user']['tags']>;
91
88
  }>) => Res<Client['listUsers']>;
92
89
  export type GetOrCreateUser<TIntegration extends BaseIntegration> = (x: Merge<Arg<Client['getOrCreateUser']>, {
93
- tags: ToTags<keyof TIntegration['user']['tags'], PrefixConfig<TIntegration>>;
90
+ tags: ToTags<keyof TIntegration['user']['tags']>;
94
91
  }>) => Promise<UserResponse<TIntegration>>;
95
92
  export type UpdateUser<TIntegration extends BaseIntegration> = (x: Merge<Arg<Client['updateUser']>, {
96
- tags: ToTags<keyof TIntegration['user']['tags'], PrefixConfig<TIntegration>>;
93
+ tags: ToTags<keyof TIntegration['user']['tags']>;
97
94
  }>) => Promise<UserResponse<TIntegration>>;
98
95
  export type DeleteUser<_TIntegration extends BaseIntegration> = Client['deleteUser'];
99
96
  type StateResponse<TIntegration extends BaseIntegration, TState extends keyof TIntegration['states']> = {
@@ -18,5 +18,5 @@ export type WithPrefix<TTags extends string, TPrefix extends PrefixConfig = null
18
18
  } ? TTags | Join<[TPrefix['allowPrefix'], ':', TTags]> : TPrefix extends {
19
19
  enforcePrefix: string;
20
20
  } ? Join<[TPrefix['enforcePrefix'], ':', TTags]> : TTags;
21
- export type ToTags<TTags extends string | number | symbol, TPrefix extends PrefixConfig = null> = AsTags<Partial<Record<WithPrefix<Cast<TTags, string>, TPrefix>, string>>>;
21
+ export type ToTags<TTags extends string | number | symbol> = AsTags<Partial<Record<Cast<TTags, string>, string>>>;
22
22
  export {};
@@ -1,5 +1,5 @@
1
- import { z } from 'zod';
2
- export declare const integrationOperationSchema: z.ZodEnum<["webhook_received", "message_created", "action_triggered", "register", "unregister", "ping", "create_user", "create_conversation"]>;
1
+ import { z } from '@bpinternal/zui';
2
+ export declare const integrationOperationSchema: import("@bpinternal/zui").ZodEnum<["webhook_received", "message_created", "action_triggered", "register", "unregister", "ping", "create_user", "create_conversation"]>;
3
3
  export type IntegrationOperation = z.infer<typeof integrationOperationSchema>;
4
4
  export type IntegrationContext<Configuration = any> = {
5
5
  botId: string;