2
0

🚸 Display error toast when script or set vari…

This commit is contained in:
Baptiste Arnaud
2024-06-11 18:18:05 +02:00
parent d80b3eaddb
commit 233ff91a57
15 changed files with 151 additions and 50 deletions

View File

@ -17,8 +17,12 @@ import {
parseTranscriptMessageText,
} from '@typebot.io/logic/computeResultTranscript'
import prisma from '@typebot.io/lib/prisma'
import { sessionOnlySetVariableOptions } from '@typebot.io/schemas/features/blocks/logic/setVariable/constants'
import {
defaultSetVariableOptions,
sessionOnlySetVariableOptions,
} from '@typebot.io/schemas/features/blocks/logic/setVariable/constants'
import { createCodeRunner } from '@typebot.io/variables/codeRunners'
import { stringifyError } from '@typebot.io/lib/stringifyError'
export const executeSetVariable = async (
state: SessionState,
@ -34,6 +38,9 @@ export const executeSetVariable = async (
block.id
)
const isCustomValue = !block.options.type || block.options.type === 'Custom'
const isCode =
(!block.options.type || block.options.type === 'Custom') &&
(block.options.isCode ?? defaultSetVariableOptions.isCode)
if (
expressionToEvaluate &&
!state.whatsApp &&
@ -50,21 +57,25 @@ export const executeSetVariable = async (
{
type: 'setVariable',
setVariable: {
scriptToExecute,
scriptToExecute: {
...scriptToExecute,
isCode,
},
},
expectsDedicatedReply: true,
},
],
}
}
const evaluatedExpression = expressionToEvaluate
? evaluateSetVariableExpression(variables)(expressionToEvaluate)
: undefined
const { value, error } =
(expressionToEvaluate
? evaluateSetVariableExpression(variables)(expressionToEvaluate)
: undefined) ?? {}
const existingVariable = variables.find(byId(block.options.variableId))
if (!existingVariable) return { outgoingEdgeId: block.outgoingEdgeId }
const newVariable = {
...existingVariable,
value: evaluatedExpression,
value,
}
const { newSetVariableHistory, updatedState } = updateVariablesInSession({
state,
@ -85,24 +96,40 @@ export const executeSetVariable = async (
outgoingEdgeId: block.outgoingEdgeId,
newSessionState: updatedState,
newSetVariableHistory,
logs:
error && isCode
? [
{
status: 'error',
description: 'Error evaluating Set variable code',
details: error,
},
]
: undefined,
}
}
const evaluateSetVariableExpression =
(variables: Variable[]) =>
(str: string): unknown => {
(str: string): { value: unknown; error?: string } => {
const isSingleVariable =
str.startsWith('{{') && str.endsWith('}}') && str.split('{{').length === 2
if (isSingleVariable) return parseVariables(variables)(str)
if (isSingleVariable) return { value: parseVariables(variables)(str) }
// To avoid octal number evaluation
if (!isNaN(str as unknown as number) && /0[^.].+/.test(str)) return str
if (!isNaN(str as unknown as number) && /0[^.].+/.test(str))
return { value: str }
try {
const body = parseVariables(variables, { fieldToParse: 'id' })(str)
return createCodeRunner({ variables })(
body.includes('return ') ? body : `return ${body}`
)
return {
value: createCodeRunner({ variables })(
body.includes('return ') ? body : `return ${body}`
),
}
} catch (err) {
return parseVariables(variables)(str)
return {
value: parseVariables(variables)(str),
error: stringifyError(err),
}
}
}

View File

@ -1,6 +1,6 @@
{
"name": "@typebot.io/js",
"version": "0.2.86",
"version": "0.2.87",
"description": "Javascript library to display typebots on your website",
"type": "module",
"main": "dist/index.js",

View File

@ -131,18 +131,18 @@ export const ConversationContainer = (props: Props) => {
)
})
const sendMessage = async (
message: string | undefined,
clientLogs?: ChatLog[]
) => {
if (clientLogs) {
props.onNewLogs?.(clientLogs)
await saveClientLogsQuery({
apiHost: props.context.apiHost,
sessionId: props.initialChatReply.sessionId,
clientLogs,
})
}
const saveLogs = async (clientLogs?: ChatLog[]) => {
if (!clientLogs) return
props.onNewLogs?.(clientLogs)
if (props.context.isPreview) return
await saveClientLogsQuery({
apiHost: props.context.apiHost,
sessionId: props.initialChatReply.sessionId,
clientLogs,
})
}
const sendMessage = async (message: string | undefined) => {
setHasError(false)
const currentInputBlock = [...chatChunks()].pop()?.input
if (currentInputBlock?.id && props.onAnswer && message)
@ -288,9 +288,10 @@ export const ConversationContainer = (props: Props) => {
},
onMessageStream: streamMessage,
})
if (response && 'logs' in response) saveLogs(response.logs)
if (response && 'replyToSend' in response) {
setIsSending(false)
sendMessage(response.replyToSend, response.logs)
sendMessage(response.replyToSend)
return
}
if (response && 'blockedPopupUrl' in response)

View File

@ -1,9 +1,13 @@
import type { ScriptToExecute } from '@typebot.io/schemas'
import { stringifyError } from '@typebot.io/lib/stringifyError'
import type { ChatLog, ScriptToExecute } from '@typebot.io/schemas'
// eslint-disable-next-line @typescript-eslint/no-empty-function
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor
export const executeScript = async ({ content, args }: ScriptToExecute) => {
export const executeScript = async ({
content,
args,
}: ScriptToExecute): Promise<void | { logs: ChatLog[] }> => {
try {
const func = AsyncFunction(
...args.map((arg) => arg.id),
@ -11,7 +15,15 @@ export const executeScript = async ({ content, args }: ScriptToExecute) => {
)
await func(...args.map((arg) => arg.value))
} catch (err) {
console.warn('Script threw an error:', err)
return {
logs: [
{
status: 'error',
description: 'Script block failed to execute',
details: stringifyError(err),
},
],
}
}
}

View File

@ -1,5 +1,6 @@
import type { ScriptToExecute } from '@typebot.io/schemas'
import type { ChatLog, ScriptToExecute } from '@typebot.io/schemas'
import { safeStringify } from '@typebot.io/lib/safeStringify'
import { stringifyError } from '@typebot.io/lib/stringifyError'
// eslint-disable-next-line @typescript-eslint/no-empty-function
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor
@ -7,7 +8,11 @@ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor
export const executeSetVariable = async ({
content,
args,
}: ScriptToExecute): Promise<{ replyToSend: string | undefined }> => {
isCode,
}: ScriptToExecute): Promise<{
replyToSend: string | undefined
logs?: ChatLog[]
}> => {
try {
// To avoid octal number evaluation
if (!isNaN(content as unknown as number) && /0[^.].+/.test(content))
@ -26,6 +31,15 @@ export const executeSetVariable = async ({
console.error(err)
return {
replyToSend: safeStringify(content) ?? undefined,
logs: isCode
? [
{
status: 'error',
description: 'Failed to execute Set Variable code',
details: stringifyError(err),
},
]
: undefined,
}
}
}

View File

@ -27,6 +27,7 @@ export const executeClientSideAction = async ({
}: Props): Promise<
| { blockedPopupUrl: string }
| { replyToSend: string | undefined; logs?: ChatLog[] }
| { logs: ChatLog[] }
| void
> => {
if ('chatwoot' in clientSideAction) {

View File

@ -1,6 +1,6 @@
{
"name": "@typebot.io/nextjs",
"version": "0.2.86",
"version": "0.2.87",
"description": "Convenient library to display typebots on your Next.js website",
"main": "dist/index.js",
"types": "dist/index.d.ts",

View File

@ -1,6 +1,6 @@
{
"name": "@typebot.io/react",
"version": "0.2.86",
"version": "0.2.87",
"description": "Convenient library to display typebots on your React app",
"main": "dist/index.js",
"types": "dist/index.d.ts",

View File

@ -0,0 +1,6 @@
export const stringifyError = (err: unknown): string =>
typeof err === 'string'
? err
: err instanceof Error
? err.name + ': ' + err.message
: JSON.stringify(err)

View File

@ -26,4 +26,5 @@ export const sessionOnlySetVariableOptions = ['Transcript'] as const
export const defaultSetVariableOptions = {
type: 'Custom',
isExecutedOnClient: false,
isCode: false,
} as const satisfies SetVariableBlock['options']

View File

@ -21,6 +21,7 @@ export type StartPropsToInject = z.infer<typeof startPropsToInjectSchema>
const scriptToExecuteSchema = z.object({
content: z.string(),
isCode: z.boolean().optional(),
args: z.array(
z.object({
id: z.string(),

View File

@ -6,6 +6,7 @@ import { safeStringify } from '@typebot.io/lib/safeStringify'
import { Variable } from './types'
import ivm from 'isolated-vm'
import { parseTransferrableValue } from './codeRunners'
import { stringifyError } from '@typebot.io/lib/stringifyError'
const defaultTimeout = 10 * 1000
@ -74,7 +75,6 @@ export const executeFunction = async ({
try {
const output = await run(parsedBody)
console.log('Output', output)
return {
output: safeStringify(output) ?? '',
newVariables: Object.entries(updatedVariables)
@ -93,12 +93,7 @@ export const executeFunction = async ({
console.log('Error while executing script')
console.error(e)
const error =
typeof e === 'string'
? e
: e instanceof Error
? e.message
: JSON.stringify(e)
const error = stringifyError(e)
return {
error,