2
0

fix: 🚑️ Webhook and instant updates

This commit is contained in:
Baptiste Arnaud
2022-02-22 10:16:35 +01:00
parent 642a42779b
commit d49461cde6
36 changed files with 317 additions and 204 deletions

View File

@ -91,13 +91,20 @@ export const BlockNode = ({ block, blockIndex }: Props) => {
})
}
const onDragStart = () => setIsMouseDown(true)
const onDragStop = () => setIsMouseDown(false)
return (
<ContextMenu<HTMLDivElement>
renderMenu={() => <BlockNodeContextMenu blockIndex={blockIndex} />}
isDisabled={isReadOnly}
>
{(ref, isOpened) => (
<DraggableCore onDrag={onDrag} onMouseDown={(e) => e.stopPropagation()}>
<DraggableCore
onDrag={onDrag}
onStart={onDragStart}
onStop={onDragStop}
onMouseDown={(e) => e.stopPropagation()}
>
<Stack
ref={setMultipleRefs([ref, blockRef])}
data-testid="block"

View File

@ -94,9 +94,14 @@ export const TypebotContext = ({
})
useEffect(() => {
if (!typebot || !localTypebot || deepEqual(typebot, localTypebot)) return
if (typebot?.blocks.length === localTypebot?.blocks.length)
setLocalTypebot({ ...typebot })
if (
!typebot ||
!localTypebot ||
typebot.updatedAt <= localTypebot.updatedAt ||
deepEqual(typebot, localTypebot)
)
return
setLocalTypebot({ ...typebot })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [typebot])
@ -113,8 +118,8 @@ export const TypebotContext = ({
] = useUndo<Typebot | undefined>(undefined)
const saveTypebot = async () => {
if (deepEqual(typebot, localTypebot)) return
const typebotToSave = currentTypebotRef.current
if (deepEqual(typebot, typebotToSave)) return
if (!typebotToSave) return
setIsSavingLoading(true)
const { error } = await updateTypebot(typebotToSave.id, typebotToSave)

View File

@ -12,7 +12,8 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.status(401).json({ message: 'Not authenticated' })
const user = session.user as User
const { code } = JSON.parse(req.body)
const { code } =
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const coupon = await prisma.coupon.findFirst({
where: { code, dateRedeemed: null },
})

View File

@ -26,7 +26,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ folders })
}
if (req.method === 'POST') {
const data = JSON.parse(req.body) as Pick<DashboardFolder, 'parentFolderId'>
const data = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as Pick<DashboardFolder, 'parentFolderId'>
const folder = await prisma.dashboardFolder.create({
data: { ...data, ownerId: user.id, name: 'New folder' },
})

View File

@ -26,7 +26,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ folders })
}
if (req.method === 'PATCH') {
const data = JSON.parse(req.body) as Partial<DashboardFolder>
const data = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as Partial<DashboardFolder>
const folders = await prisma.dashboardFolder.update({
where: { id_ownerId: { id, ownerId: user.id } },
data,

View File

@ -5,8 +5,9 @@ import { createTransport } from 'nodemailer'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const { from, port, isTlsEnabled, username, password, host, to } =
JSON.parse(req.body) as SmtpCredentialsData & { to: string }
const { from, port, isTlsEnabled, username, password, host, to } = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as SmtpCredentialsData & { to: string }
const transporter = createTransport({
host,
port,

View File

@ -12,7 +12,8 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
try {
if (req.method === 'POST') {
const data = JSON.parse(req.body)
const data =
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebot = await prisma.publicTypebot.create({
data: { ...data },
})

View File

@ -12,7 +12,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const id = req.query.id.toString()
if (req.method === 'PUT') {
const data = JSON.parse(req.body)
const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebots = await prisma.publicTypebot.update({
where: { id },
data,

View File

@ -10,7 +10,8 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2020-08-27',
})
const { email, currency } = JSON.parse(req.body)
const { email, currency } =
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const session = await stripe.checkout.sessions.create({
success_url: `${req.headers.origin}/typebots?stripe=success`,
cancel_url: `${req.headers.origin}/typebots?stripe=cancel`,

View File

@ -26,7 +26,8 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ typebots })
}
if (req.method === 'POST') {
const data = JSON.parse(req.body)
const data =
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebot = await prisma.typebot.create({
data:
'blocks' in data

View File

@ -41,7 +41,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ typebots })
}
if (req.method === 'PUT') {
const data = JSON.parse(req.body)
const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebots = await prisma.typebot.update({
where: { id_ownerId: { id: typebotId, ownerId: user.id } },
data: {
@ -53,7 +53,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ typebots })
}
if (req.method === 'PATCH') {
const data = JSON.parse(req.body)
const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebots = await prisma.typebot.update({
where: { id_ownerId: { id: typebotId, ownerId: user.id } },
data,

View File

@ -12,7 +12,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const id = req.query.id.toString()
if (req.method === 'PUT') {
const data = JSON.parse(req.body)
const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebots = await prisma.user.update({
where: { id },
data,

View File

@ -23,7 +23,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ credentials })
}
if (req.method === 'POST') {
const data = JSON.parse(req.body) as Omit<Credentials, 'ownerId'>
const data = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as Omit<Credentials, 'ownerId'>
const { encryptedData, iv } = encrypt(data.data)
const credentials = await prisma.credentials.create({
data: {

View File

@ -22,7 +22,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return res.send({ customDomains })
}
if (req.method === 'POST') {
const data = JSON.parse(req.body) as Omit<CustomDomain, 'ownerId'>
const data = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as Omit<CustomDomain, 'ownerId'>
try {
await createDomainOnVercel(data.name)
} catch (err) {

View File

@ -129,7 +129,7 @@ const createAnswers = () => {
const parseTypebotToPublicTypebot = (
id: string,
typebot: Typebot
): PublicTypebot => ({
): Omit<PublicTypebot, 'createdAt' | 'updatedAt'> => ({
id,
name: typebot.name,
blocks: parseBlocksToPublicBlocks(typebot.blocks),
@ -157,10 +157,9 @@ const parseTestTypebot = (partialTypebot: Partial<Typebot>): Typebot => ({
ownerId: 'proUser',
theme: defaultTheme,
settings: defaultSettings,
createdAt: new Date(),
publicId: null,
publishedTypebotId: null,
updatedAt: new Date(),
publishedTypebotId: null,
customDomain: null,
variables: [{ id: 'var1', name: 'var1' }],
...partialTypebot,

View File

@ -6,7 +6,7 @@ import path from 'path'
const typebotId = generate()
test.describe('Dashboard page', () => {
test('folders navigation should work', async ({ page }) => {
test('should be able to connect custom domain', async ({ page }) => {
await createTypebots([
{
id: typebotId,

View File

@ -6,7 +6,9 @@ import { methodNotAllowed } from 'utils'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'PUT') {
const answer = JSON.parse(req.body) as Answer
const answer = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as Answer
const result = await prisma.answer.upsert({
where: {
resultId_blockId_stepId: {

View File

@ -27,8 +27,8 @@ const defaultFrom = {
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
await cors(req, res)
if (req.method === 'POST') {
const { credentialsId, recipients, body, subject, cc, bcc } = JSON.parse(
req.body
const { credentialsId, recipients, body, subject, cc, bcc } = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as SendEmailOptions
const { host, port, isTlsEnabled, username, password, from } =

View File

@ -37,7 +37,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const spreadsheetId = req.query.spreadsheetId.toString()
const sheetId = req.query.sheetId.toString()
const { credentialsId, values } = JSON.parse(req.body) as {
const { credentialsId, values } = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as {
credentialsId: string
values: { [key: string]: string }
}
@ -51,7 +53,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'PATCH') {
const spreadsheetId = req.query.spreadsheetId.toString()
const sheetId = req.query.sheetId.toString()
const { credentialsId, values, referenceCell } = JSON.parse(req.body) as {
const { credentialsId, values, referenceCell } = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as {
credentialsId: string
referenceCell: Cell
values: { [key: string]: string }

View File

@ -6,7 +6,9 @@ import { methodNotAllowed } from 'utils'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const resultData = JSON.parse(req.body) as {
const resultData = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as {
typebotId: string
prefilledVariables: VariableWithValue[]
}

View File

@ -5,7 +5,9 @@ import { methodNotAllowed } from 'utils'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'PATCH') {
const data = JSON.parse(req.body) as { isCompleted: true }
const data = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as { isCompleted: true }
const id = req.query.id.toString()
const result = await prisma.result.update({
where: { id },

View File

@ -1,12 +1,21 @@
import prisma from 'libs/prisma'
import { KeyValue, Typebot, Variable, Webhook, WebhookResponse } from 'models'
import {
KeyValue,
PublicTypebot,
ResultValues,
Typebot,
Variable,
Webhook,
WebhookResponse,
} from 'models'
import { parseVariables } from 'bot-engine'
import { NextApiRequest, NextApiResponse } from 'next'
import got, { Method, Headers, HTTPError } from 'got'
import { byId, initMiddleware, methodNotAllowed } from 'utils'
import { byId, initMiddleware, methodNotAllowed, parseAnswers } from 'utils'
import { stringify } from 'qs'
import { withSentry } from '@sentry/nextjs'
import Cors from 'cors'
import { parseSampleResult } from 'services/api/webhooks'
const cors = initMiddleware(Cors())
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
@ -15,87 +24,125 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const typebotId = req.query.typebotId.toString()
const blockId = req.query.blockId.toString()
const stepId = req.query.stepId.toString()
const variables = JSON.parse(req.body).variables as Variable[]
const typebot = await prisma.typebot.findUnique({
const { resultValues, variables } = (
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
) as {
resultValues: ResultValues | undefined
variables: Variable[]
}
const typebot = (await prisma.typebot.findUnique({
where: { id: typebotId },
})
const step = (typebot as unknown as Typebot).blocks
.find(byId(blockId))
?.steps.find(byId(stepId))
})) as unknown as Typebot
const step = typebot.blocks.find(byId(blockId))?.steps.find(byId(stepId))
if (!step || !('webhook' in step))
return res
.status(404)
.send({ statusCode: 404, data: { message: `Couldn't find webhook` } })
const result = await executeWebhook(step.webhook, variables)
const result = await executeWebhook(typebot)(
step.webhook,
variables,
blockId,
resultValues
)
return res.status(200).send(result)
}
return methodNotAllowed(res)
}
const executeWebhook = async (
webhook: Webhook,
variables: Variable[]
): Promise<WebhookResponse> => {
if (!webhook.url || !webhook.method)
return {
statusCode: 400,
data: { message: `Webhook doesn't have url or method` },
}
const basicAuth: { username?: string; password?: string } = {}
const basicAuthHeaderIdx = webhook.headers.findIndex(
(h) =>
h.key?.toLowerCase() === 'authorization' &&
h.value?.toLowerCase().includes('basic')
)
if (basicAuthHeaderIdx !== -1) {
const [username, password] =
webhook.headers[basicAuthHeaderIdx].value?.slice(6).split(':') ?? []
basicAuth.username = username
basicAuth.password = password
webhook.headers.splice(basicAuthHeaderIdx, 1)
}
const headers = convertKeyValueTableToObject(webhook.headers, variables) as
| Headers
| undefined
const queryParams = stringify(
convertKeyValueTableToObject(webhook.queryParams, variables)
)
const contentType = headers ? headers['Content-Type'] : undefined
try {
const response = await got(
parseVariables(variables)(webhook.url + `?${queryParams}`),
{
method: webhook.method as Method,
headers,
...basicAuth,
json:
contentType !== 'x-www-form-urlencoded' && webhook.body
? JSON.parse(parseVariables(variables)(webhook.body))
: undefined,
form:
contentType === 'x-www-form-urlencoded' && webhook.body
? JSON.parse(parseVariables(variables)(webhook.body))
: undefined,
}
)
return {
statusCode: response.statusCode,
data: parseBody(response.body),
}
} catch (error) {
if (error instanceof HTTPError) {
const executeWebhook =
(typebot: Typebot) =>
async (
webhook: Webhook,
variables: Variable[],
blockId: string,
resultValues?: ResultValues
): Promise<WebhookResponse> => {
if (!webhook.url || !webhook.method)
return {
statusCode: error.response.statusCode,
data: parseBody(error.response.body as string),
statusCode: 400,
data: { message: `Webhook doesn't have url or method` },
}
const basicAuth: { username?: string; password?: string } = {}
const basicAuthHeaderIdx = webhook.headers.findIndex(
(h) =>
h.key?.toLowerCase() === 'authorization' &&
h.value?.toLowerCase().includes('basic')
)
if (basicAuthHeaderIdx !== -1) {
const [username, password] =
webhook.headers[basicAuthHeaderIdx].value?.slice(6).split(':') ?? []
basicAuth.username = username
basicAuth.password = password
webhook.headers.splice(basicAuthHeaderIdx, 1)
}
const headers = convertKeyValueTableToObject(webhook.headers, variables) as
| Headers
| undefined
const queryParams = stringify(
convertKeyValueTableToObject(webhook.queryParams, variables)
)
const contentType = headers ? headers['Content-Type'] : undefined
const body = getBodyContent(typebot)({
body: webhook.body,
resultValues,
blockId,
})
try {
const response = await got(
parseVariables(variables)(webhook.url + `?${queryParams}`),
{
method: webhook.method as Method,
headers,
...basicAuth,
json:
contentType !== 'x-www-form-urlencoded' && body
? JSON.parse(parseVariables(variables)(body))
: undefined,
form:
contentType === 'x-www-form-urlencoded' && body
? JSON.parse(parseVariables(variables)(body))
: undefined,
}
)
return {
statusCode: response.statusCode,
data: parseBody(response.body),
}
} catch (error) {
if (error instanceof HTTPError) {
return {
statusCode: error.response.statusCode,
data: parseBody(error.response.body as string),
}
}
console.error(error)
return {
statusCode: 500,
data: { message: `Error from Typebot server: ${error}` },
}
}
console.error(error)
return {
statusCode: 500,
data: { message: `Error from Typebot server: ${error}` },
}
}
}
const getBodyContent =
(typebot: Pick<Typebot | PublicTypebot, 'blocks' | 'variables' | 'edges'>) =>
({
body,
resultValues,
blockId,
}: {
body?: string
resultValues?: ResultValues
blockId: string
}): string | undefined => {
if (!body) return
return body === '{{state}}'
? JSON.stringify(
resultValues
? parseAnswers(typebot)(resultValues)
: parseSampleResult(typebot)(blockId)
)
: body
}
const parseBody = (body: string) => {
try {

View File

@ -1,8 +1,9 @@
import prisma from 'libs/prisma'
import { Block, InputStep, InputStepType, Typebot } from 'models'
import { Typebot } from 'models'
import { NextApiRequest, NextApiResponse } from 'next'
import { authenticateUser } from 'services/api/utils'
import { byId, isDefined, isInputStep, methodNotAllowed } from 'utils'
import { parseSampleResult } from 'services/api/webhooks'
import { methodNotAllowed } from 'utils'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'GET') {
@ -12,87 +13,11 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const blockId = req.query.blockId.toString()
const typebot = (await prisma.typebot.findUnique({
where: { id_ownerId: { id: typebotId, ownerId: user.id } },
})) as Typebot | undefined
})) as unknown as Typebot | undefined
if (!typebot) return res.status(400).send({ message: 'Typebot not found' })
const previousBlockIds = getPreviousBlocks(typebot)(blockId)
const previousBlocks = typebot.blocks.filter((b) =>
previousBlockIds.includes(b.id)
)
return res.send(parseSampleResult(typebot)(previousBlocks))
return res.send(parseSampleResult(typebot)(blockId))
}
methodNotAllowed(res)
}
const parseSampleResult =
(typebot: Typebot) =>
(blocks: Block[]): Record<string, string> => {
const parsedBlocks = parseBlocksResultSample(typebot, blocks)
return {
message: 'This is a sample result, it has been generated ⬇️',
'Submitted at': new Date().toISOString(),
...parsedBlocks,
...parseVariablesHeaders(typebot, parsedBlocks),
}
}
const parseBlocksResultSample = (typebot: Typebot, blocks: Block[]) =>
blocks
.filter((block) => typebot && block.steps.some((step) => isInputStep(step)))
.reduce<Record<string, string>>((blocks, block) => {
const inputStep = block.steps.find((step) => isInputStep(step))
if (!inputStep || !isInputStep(inputStep)) return blocks
const matchedVariableName =
inputStep.options.variableId &&
typebot.variables.find(byId(inputStep.options.variableId))?.name
const value = getSampleValue(inputStep)
return {
...blocks,
[matchedVariableName ?? block.title]: value,
}
}, {})
const getSampleValue = (step: InputStep) => {
switch (step.type) {
case InputStepType.CHOICE:
return 'Item 1, Item 2, Item3'
case InputStepType.DATE:
return new Date().toUTCString()
case InputStepType.EMAIL:
return 'test@email.com'
case InputStepType.NUMBER:
return '20'
case InputStepType.PHONE:
return '+33665566773'
case InputStepType.TEXT:
return 'answer value'
case InputStepType.URL:
return 'https://test.com'
}
}
const parseVariablesHeaders = (
typebot: Typebot,
parsedBlocks: Record<string, string>
) =>
typebot.variables.reduce<Record<string, string>>((headers, v) => {
if (parsedBlocks[v.name]) return headers
return {
...headers,
[v.name]: 'value',
}
}, {})
const getPreviousBlocks =
(typebot: Typebot) =>
(blockId: string): string[] => {
const previousBlocks = typebot.edges
.map((edge) =>
edge.to.blockId === blockId ? edge.from.blockId : undefined
)
.filter(isDefined)
return previousBlocks.concat(
previousBlocks.flatMap(getPreviousBlocks(typebot))
)
}
export default handler

View File

@ -18,7 +18,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const stepId = req.query.stepId.toString()
const typebot = (await prisma.typebot.findUnique({
where: { id_ownerId: { id: typebotId, ownerId: user.id } },
})) as Typebot | undefined
})) as unknown as Typebot | undefined
if (!typebot) return res.status(400).send({ message: 'Typebot not found' })
try {
const updatedTypebot = addUrlToWebhookStep(url, typebot, stepId)

View File

@ -15,7 +15,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const stepId = req.query.stepId.toString()
const typebot = (await prisma.typebot.findUnique({
where: { id_ownerId: { id: typebotId, ownerId: user.id } },
})) as Typebot | undefined
})) as unknown as Typebot | undefined
if (!typebot) return res.status(400).send({ message: 'Typebot not found' })
try {
const updatedTypebot = removeUrlFromWebhookStep(typebot, stepId)

View File

@ -20,7 +20,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
take: limit,
include: { answers: true },
})) as unknown as ResultWithAnswers[]
res.send({ results: results.map(parseAnswers(typebot as Typebot)) })
res.send({
results: results.map(parseAnswers(typebot as unknown as Typebot)),
})
}
methodNotAllowed(res)
}

View File

@ -74,7 +74,6 @@ const parseTestTypebot = (partialTypebot: Partial<Typebot>): Typebot => ({
ownerId: 'user',
theme: defaultTheme,
settings: defaultSettings,
createdAt: new Date(),
publicId: partialTypebot.id + '-public',
publishedTypebotId: null,
updatedAt: new Date(),

View File

@ -0,0 +1,80 @@
import { Block, InputStep, InputStepType, PublicTypebot, Typebot } from 'models'
import { isInputStep, byId, isDefined } from 'utils'
export const parseSampleResult =
(typebot: Pick<Typebot | PublicTypebot, 'blocks' | 'variables' | 'edges'>) =>
(currentBlockId: string): Record<string, string> => {
const previousBlocks = (typebot.blocks as Block[]).filter((b) =>
getPreviousBlockIds(typebot)(currentBlockId).includes(b.id)
)
const parsedBlocks = parseBlocksResultSample(typebot, previousBlocks)
return {
message: 'This is a sample result, it has been generated ⬇️',
'Submitted at': new Date().toISOString(),
...parsedBlocks,
...parseVariablesHeaders(typebot, parsedBlocks),
}
}
const parseBlocksResultSample = (
typebot: Pick<Typebot | PublicTypebot, 'blocks' | 'variables'>,
blocks: Block[]
) =>
blocks
.filter((block) => typebot && block.steps.some((step) => isInputStep(step)))
.reduce<Record<string, string>>((blocks, block) => {
const inputStep = block.steps.find((step) => isInputStep(step))
if (!inputStep || !isInputStep(inputStep)) return blocks
const matchedVariableName =
inputStep.options.variableId &&
typebot.variables.find(byId(inputStep.options.variableId))?.name
const value = getSampleValue(inputStep)
return {
...blocks,
[matchedVariableName ?? block.title]: value,
}
}, {})
const getSampleValue = (step: InputStep) => {
switch (step.type) {
case InputStepType.CHOICE:
return 'Item 1, Item 2, Item3'
case InputStepType.DATE:
return new Date().toUTCString()
case InputStepType.EMAIL:
return 'test@email.com'
case InputStepType.NUMBER:
return '20'
case InputStepType.PHONE:
return '+33665566773'
case InputStepType.TEXT:
return 'answer value'
case InputStepType.URL:
return 'https://test.com'
}
}
const parseVariablesHeaders = (
typebot: Pick<Typebot | PublicTypebot, 'blocks' | 'variables'>,
parsedBlocks: Record<string, string>
) =>
typebot.variables.reduce<Record<string, string>>((headers, v) => {
if (parsedBlocks[v.name]) return headers
return {
...headers,
[v.name]: 'value',
}
}, {})
const getPreviousBlockIds =
(typebot: Pick<Typebot | PublicTypebot, 'blocks' | 'variables' | 'edges'>) =>
(blockId: string): string[] => {
const previousBlocks = typebot.edges
.map((edge) =>
edge.to.blockId === blockId ? edge.from.blockId : undefined
)
.filter(isDefined)
return previousBlocks.concat(
previousBlocks.flatMap(getPreviousBlockIds(typebot))
)
}