@adatechnology/meta-whatsapp-module 0.8.1 → 0.10.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.
package/dist/index.js CHANGED
@@ -10,7 +10,8 @@ var __dirname = /* @__PURE__ */ getDirname();
10
10
 
11
11
  // src/createMetaWhatsAppModule.ts
12
12
  import { WhatsAppMessageProvider } from "@adatechnology/meta-whatsapp-provider";
13
- import { FLOW_ACTION_KIND } from "@adatechnology/meta-whatsapp-contracts";
13
+ import { buildPreviewInboundPayload } from "@adatechnology/meta-whatsapp-contracts/testing";
14
+ import { ConfigMissingError as ConfigMissingError2, FLOW_ACTION_KIND } from "@adatechnology/meta-whatsapp-contracts";
14
15
 
15
16
  // src/repositories/SessionRepository.ts
16
17
  import { and, desc, eq, sql as sql2 } from "drizzle-orm";
@@ -399,6 +400,21 @@ var SessionRepository = class {
399
400
  updatedAt: sql2`now()`
400
401
  }).where(and(eq(sessions.companyId, companyId), eq(sessions.whatsappNumber, whatsappNumber)));
401
402
  }
403
+ /**
404
+ * Posição no grafo e contexto numa escrita só — é o que o runner grava a cada mensagem. Em duas
405
+ * escritas, uma falha no meio deixaria a conversa num nó novo com as respostas do anterior.
406
+ * Não toca em `currentState`, `mode` nem `humanRequestedAt`: uma ação de encaminhamento que rodou
407
+ * no mesmo passo já os mudou, e regravá-los desfaria isso.
408
+ */
409
+ async saveFlowProgress(companyId, whatsappNumber, progress) {
410
+ await this.db.update(sessions).set({
411
+ flowKey: progress.flowKey,
412
+ currentNodeId: progress.currentNodeId,
413
+ context: progress.context,
414
+ lastActivity: sql2`now()`,
415
+ updatedAt: sql2`now()`
416
+ }).where(and(eq(sessions.companyId, companyId), eq(sessions.whatsappNumber, whatsappNumber)));
417
+ }
402
418
  // Marca a chegada de uma mensagem DO CLIENTE. É este carimbo — e não lastActivity, que também
403
419
  // se move em ações do atendente/bot — que define a janela de 24h do WhatsApp: fora dela, só
404
420
  // template aprovado reabre a conversa (ver WindowExpiredError nos contracts).
@@ -1010,8 +1026,9 @@ var LogMessageUseCase = class {
1010
1026
  };
1011
1027
 
1012
1028
  // src/use-cases/SendMessage.use-case.ts
1013
- import { WindowExpiredError } from "@adatechnology/meta-whatsapp-contracts";
1029
+ import { WindowExpiredError, assertInteractiveWithinLimits } from "@adatechnology/meta-whatsapp-contracts";
1014
1030
  var WHATSAPP_WINDOW_HOURS = 24;
1031
+ var DEFAULT_FALLBACK_LIST_LABEL = "Op\xE7\xF5es";
1015
1032
  var SendMessageUseCase = class {
1016
1033
  static {
1017
1034
  __name(this, "SendMessageUseCase");
@@ -1096,6 +1113,54 @@ var SendMessageUseCase = class {
1096
1113
  }
1097
1114
  return saved;
1098
1115
  }
1116
+ /**
1117
+ * Botões ou lista, pelo mesmo caminho do `sendText`: janela, envio, transcript (idempotente pelo
1118
+ * `waMessageId`). Os limites da Meta são conferidos ANTES de tudo — mensagem fora do teto a Graph
1119
+ * API recusa inteira, e o erro local (`InteractiveLimitExceededError`) diz qual campo corrigir.
1120
+ *
1121
+ * O transcript guarda `type: 'interactive'`, o corpo em `content` e a mensagem inteira (ids e
1122
+ * títulos das opções) em `payload.interactive`, para o histórico mostrar o que foi oferecido.
1123
+ */
1124
+ async sendInteractive(params) {
1125
+ assertInteractiveWithinLimits(params.interactive);
1126
+ await this.assertWithinWindow(params.companyId, params.whatsappNumber);
1127
+ const { externalMessageId } = await this.sendInteractiveThroughChannel(params);
1128
+ return this.logMessage.execute({
1129
+ companyId: params.companyId,
1130
+ whatsappNumber: params.whatsappNumber,
1131
+ direction: "outbound",
1132
+ sender: params.sender,
1133
+ agentUserId: params.agentUserId ?? null,
1134
+ type: "interactive",
1135
+ content: params.interactive.body,
1136
+ payload: {
1137
+ interactive: params.interactive
1138
+ },
1139
+ waMessageId: externalMessageId,
1140
+ status: "sent",
1141
+ startState: params.startState
1142
+ });
1143
+ }
1144
+ sendInteractiveThroughChannel(params) {
1145
+ const interactive = params.interactive;
1146
+ const to = params.whatsappNumber;
1147
+ if (interactive.kind === "list") {
1148
+ return this.channel.sendInteractiveList({
1149
+ to,
1150
+ body: interactive.body,
1151
+ buttonLabel: interactive.buttonLabel,
1152
+ sections: interactive.sections
1153
+ });
1154
+ }
1155
+ if (this.channel.sendInteractiveButtons) {
1156
+ return this.channel.sendInteractiveButtons({
1157
+ to,
1158
+ body: interactive.body,
1159
+ buttons: interactive.buttons
1160
+ });
1161
+ }
1162
+ return this.channel.sendInteractiveList(buttonsAsList(interactive, to, params.fallbackListLabel));
1163
+ }
1099
1164
  // Template é o único envio que ignora a janela — é justamente o mecanismo que a Meta oferece
1100
1165
  // para reabri-la.
1101
1166
  async sendTemplate(params) {
@@ -1123,6 +1188,15 @@ var SendMessageUseCase = class {
1123
1188
  });
1124
1189
  }
1125
1190
  };
1191
+ function buttonsAsList(interactive, to, label) {
1192
+ return {
1193
+ to,
1194
+ body: interactive.body,
1195
+ buttonLabel: label ?? DEFAULT_FALLBACK_LIST_LABEL,
1196
+ rows: interactive.buttons
1197
+ };
1198
+ }
1199
+ __name(buttonsAsList, "buttonsAsList");
1126
1200
  function mediaTypeFor(mimeType) {
1127
1201
  if (mimeType.startsWith("image/")) return "image";
1128
1202
  if (mimeType.startsWith("audio/")) return "audio";
@@ -1138,9 +1212,11 @@ var TakeoverConversationUseCase = class {
1138
1212
  }
1139
1213
  sessionRepository;
1140
1214
  realtime;
1141
- constructor(sessionRepository, realtime) {
1215
+ hooks;
1216
+ constructor(sessionRepository, realtime, hooks) {
1142
1217
  this.sessionRepository = sessionRepository;
1143
1218
  this.realtime = realtime;
1219
+ this.hooks = hooks;
1144
1220
  }
1145
1221
  async execute(params) {
1146
1222
  await this.sessionRepository.takeover(params.companyId, params.whatsappNumber, params.agentUserId);
@@ -1149,6 +1225,15 @@ var TakeoverConversationUseCase = class {
1149
1225
  assignedUserId: params.agentUserId
1150
1226
  });
1151
1227
  this.realtime?.emit("global", "data-changed", {});
1228
+ await this.hooks?.onConversationModeChanged?.({
1229
+ companyId: params.companyId,
1230
+ whatsappNumber: params.whatsappNumber,
1231
+ kind: "takeover",
1232
+ mode: "human",
1233
+ assignedUserId: params.agentUserId,
1234
+ actorId: params.actorId ?? params.agentUserId,
1235
+ occurredAt: /* @__PURE__ */ new Date()
1236
+ });
1152
1237
  }
1153
1238
  };
1154
1239
 
@@ -1159,9 +1244,11 @@ var ReleaseConversationUseCase = class {
1159
1244
  }
1160
1245
  sessionRepository;
1161
1246
  realtime;
1162
- constructor(sessionRepository, realtime) {
1247
+ hooks;
1248
+ constructor(sessionRepository, realtime, hooks) {
1163
1249
  this.sessionRepository = sessionRepository;
1164
1250
  this.realtime = realtime;
1251
+ this.hooks = hooks;
1165
1252
  }
1166
1253
  async execute(params) {
1167
1254
  await this.sessionRepository.release(params.companyId, params.whatsappNumber);
@@ -1170,6 +1257,165 @@ var ReleaseConversationUseCase = class {
1170
1257
  assignedUserId: null
1171
1258
  });
1172
1259
  this.realtime?.emit("global", "data-changed", {});
1260
+ await this.hooks?.onConversationModeChanged?.({
1261
+ companyId: params.companyId,
1262
+ whatsappNumber: params.whatsappNumber,
1263
+ kind: "release",
1264
+ mode: "bot",
1265
+ assignedUserId: null,
1266
+ actorId: params.actorId ?? null,
1267
+ occurredAt: /* @__PURE__ */ new Date()
1268
+ });
1269
+ }
1270
+ };
1271
+
1272
+ // src/use-cases/RequestHumanConversation.use-case.ts
1273
+ import { SessionNotFoundError } from "@adatechnology/meta-whatsapp-contracts";
1274
+
1275
+ // src/channel/inboundDispatch.ts
1276
+ import { isDeterministicMetaRejection } from "@adatechnology/meta-graph-core";
1277
+ function buildInboundJobId(job) {
1278
+ return job.kind === "message" ? `wa-inbound-message:${job.message.id}` : `wa-inbound-status:${job.status.id}:${job.status.status}`;
1279
+ }
1280
+ __name(buildInboundJobId, "buildInboundJobId");
1281
+ function toSessionContract(row) {
1282
+ return {
1283
+ id: row.id,
1284
+ companyId: row.companyId,
1285
+ whatsappNumber: row.whatsappNumber,
1286
+ currentState: row.currentState,
1287
+ flowKey: row.flowKey,
1288
+ currentNodeId: row.currentNodeId,
1289
+ context: row.context,
1290
+ mode: row.mode,
1291
+ assignedUserId: row.assignedUserId,
1292
+ humanRequestedAt: row.humanRequestedAt?.toISOString() ?? null,
1293
+ lastInboundAt: row.lastInboundAt?.toISOString() ?? null,
1294
+ lastAgentReadAt: row.lastAgentReadAt?.toISOString() ?? null,
1295
+ lastActivity: row.lastActivity.toISOString(),
1296
+ createdAt: row.createdAt.toISOString(),
1297
+ updatedAt: row.updatedAt.toISOString()
1298
+ };
1299
+ }
1300
+ __name(toSessionContract, "toSessionContract");
1301
+ var InboundEffectsDispatcher = class {
1302
+ static {
1303
+ __name(this, "InboundEffectsDispatcher");
1304
+ }
1305
+ params;
1306
+ constructor(params) {
1307
+ this.params = params;
1308
+ }
1309
+ async run(job) {
1310
+ if (job.kind === "message") return this.runMessageEffects(job);
1311
+ return this.runStatusEffects(job);
1312
+ }
1313
+ async runMessageEffects(job) {
1314
+ const { companyId, message, savedMessageId, media } = job;
1315
+ if (media) {
1316
+ await this.params.hooks?.onMediaReceived?.({
1317
+ companyId,
1318
+ messageId: savedMessageId,
1319
+ whatsappNumber: message.from,
1320
+ sourceMediaId: media.sourceMediaId,
1321
+ mimeType: media.mimeType,
1322
+ ...media.filename ? {
1323
+ filename: media.filename
1324
+ } : {}
1325
+ });
1326
+ }
1327
+ const sessionRow = await this.params.sessionRepository.getContext(companyId, message.from);
1328
+ if (!sessionRow) return;
1329
+ if (sessionRow.mode === "human") return;
1330
+ const outcome = await this.params.hooks?.onMessageReceived?.(message, toSessionContract(sessionRow), job.profileName === void 0 ? {} : {
1331
+ profileName: job.profileName
1332
+ });
1333
+ if (outcome?.outcome === "handled") return;
1334
+ await this.params.flowRunner?.handle({
1335
+ companyId,
1336
+ message,
1337
+ ...job.profileName === void 0 ? {} : {
1338
+ profileName: job.profileName
1339
+ }
1340
+ });
1341
+ }
1342
+ async runStatusEffects(job) {
1343
+ const sessionRow = await this.params.sessionRepository.getContext(job.companyId, job.whatsappNumber);
1344
+ await this.params.hooks?.onStatusUpdate?.(job.status, sessionRow ? toSessionContract(sessionRow) : null);
1345
+ }
1346
+ };
1347
+ var ProcessInboundDispatchUseCase = class {
1348
+ static {
1349
+ __name(this, "ProcessInboundDispatchUseCase");
1350
+ }
1351
+ dispatcher;
1352
+ hooks;
1353
+ constructor(dispatcher, hooks) {
1354
+ this.dispatcher = dispatcher;
1355
+ this.hooks = hooks;
1356
+ }
1357
+ async execute(job) {
1358
+ await runInboundEffects({
1359
+ dispatcher: this.dispatcher,
1360
+ job,
1361
+ ...this.hooks ? {
1362
+ hooks: this.hooks
1363
+ } : {}
1364
+ });
1365
+ }
1366
+ };
1367
+ async function runInboundEffects(params) {
1368
+ const { job } = params;
1369
+ try {
1370
+ await params.dispatcher.run(job);
1371
+ } catch (error) {
1372
+ if (!isDeterministicMetaRejection(error)) throw error;
1373
+ await params.hooks?.onInboundEffectRejected?.({
1374
+ companyId: job.companyId,
1375
+ kind: job.kind,
1376
+ whatsappNumber: job.kind === "message" ? job.message.from : job.whatsappNumber,
1377
+ code: error.code,
1378
+ error
1379
+ });
1380
+ }
1381
+ }
1382
+ __name(runInboundEffects, "runInboundEffects");
1383
+
1384
+ // src/use-cases/RequestHumanConversation.use-case.ts
1385
+ var RequestHumanConversationUseCase = class {
1386
+ static {
1387
+ __name(this, "RequestHumanConversationUseCase");
1388
+ }
1389
+ sessionRepository;
1390
+ realtime;
1391
+ hooks;
1392
+ constructor(sessionRepository, realtime, hooks) {
1393
+ this.sessionRepository = sessionRepository;
1394
+ this.realtime = realtime;
1395
+ this.hooks = hooks;
1396
+ }
1397
+ async execute(params) {
1398
+ await this.sessionRepository.requestHuman(params.companyId, params.whatsappNumber);
1399
+ const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
1400
+ if (!session) throw new SessionNotFoundError(params.whatsappNumber);
1401
+ this.realtime?.emit(`conv:${params.whatsappNumber}`, "human-requested", {
1402
+ humanRequestedAt: session.humanRequestedAt?.toISOString() ?? null
1403
+ });
1404
+ this.realtime?.emit("global", "data-changed", {});
1405
+ const outcomes = await Promise.allSettled([
1406
+ (async () => this.hooks?.onHumanRequested?.(toSessionContract(session)))(),
1407
+ (async () => this.hooks?.onConversationModeChanged?.({
1408
+ companyId: params.companyId,
1409
+ whatsappNumber: params.whatsappNumber,
1410
+ kind: "human-requested",
1411
+ mode: session.mode,
1412
+ assignedUserId: session.assignedUserId,
1413
+ actorId: params.actorId ?? null,
1414
+ occurredAt: /* @__PURE__ */ new Date()
1415
+ }))()
1416
+ ]);
1417
+ const failure = outcomes.find((outcome) => outcome.status === "rejected");
1418
+ if (failure) throw failure.reason;
1173
1419
  }
1174
1420
  };
1175
1421
 
@@ -1188,7 +1434,7 @@ var ListConversationsUseCase = class {
1188
1434
  };
1189
1435
 
1190
1436
  // src/use-cases/ListMessages.use-case.ts
1191
- import { SessionNotFoundError } from "@adatechnology/meta-whatsapp-contracts";
1437
+ import { SessionNotFoundError as SessionNotFoundError2 } from "@adatechnology/meta-whatsapp-contracts";
1192
1438
  var ListMessagesUseCase = class {
1193
1439
  static {
1194
1440
  __name(this, "ListMessagesUseCase");
@@ -1201,7 +1447,7 @@ var ListMessagesUseCase = class {
1201
1447
  }
1202
1448
  async execute(params) {
1203
1449
  const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
1204
- if (!session) throw new SessionNotFoundError(params.whatsappNumber);
1450
+ if (!session) throw new SessionNotFoundError2(params.whatsappNumber);
1205
1451
  const repoParams = {
1206
1452
  companyId: params.companyId,
1207
1453
  sessionId: session.id,
@@ -1213,7 +1459,7 @@ var ListMessagesUseCase = class {
1213
1459
  };
1214
1460
 
1215
1461
  // src/use-cases/ListConversationDocuments.use-case.ts
1216
- import { SessionNotFoundError as SessionNotFoundError2 } from "@adatechnology/meta-whatsapp-contracts";
1462
+ import { SessionNotFoundError as SessionNotFoundError3 } from "@adatechnology/meta-whatsapp-contracts";
1217
1463
  var ListConversationDocumentsUseCase = class {
1218
1464
  static {
1219
1465
  __name(this, "ListConversationDocumentsUseCase");
@@ -1226,7 +1472,7 @@ var ListConversationDocumentsUseCase = class {
1226
1472
  }
1227
1473
  async execute(params) {
1228
1474
  const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
1229
- if (!session) throw new SessionNotFoundError2(params.whatsappNumber);
1475
+ if (!session) throw new SessionNotFoundError3(params.whatsappNumber);
1230
1476
  const { rows, total } = await this.documentRepository.listByConversation({
1231
1477
  companyId: params.companyId,
1232
1478
  sessionId: session.id,
@@ -1304,7 +1550,7 @@ var ListCompanyDocumentsUseCase = class {
1304
1550
  };
1305
1551
 
1306
1552
  // src/use-cases/DeleteConversation.use-case.ts
1307
- import { SessionNotFoundError as SessionNotFoundError3 } from "@adatechnology/meta-whatsapp-contracts";
1553
+ import { SessionNotFoundError as SessionNotFoundError4 } from "@adatechnology/meta-whatsapp-contracts";
1308
1554
  var DeleteConversationUseCase = class {
1309
1555
  static {
1310
1556
  __name(this, "DeleteConversationUseCase");
@@ -1319,7 +1565,7 @@ var DeleteConversationUseCase = class {
1319
1565
  }
1320
1566
  async execute(params) {
1321
1567
  const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
1322
- if (!session) throw new SessionNotFoundError3(params.whatsappNumber);
1568
+ if (!session) throw new SessionNotFoundError4(params.whatsappNumber);
1323
1569
  const uploadIds = await this.documentRepository.listUploadIdsBySession(params.companyId, session.id);
1324
1570
  if (uploadIds.length > 0 && !this.objectStorage?.delete) {
1325
1571
  throw new Error("storage_delete_unsupported: a conversa tem arquivos e o storage injetado n\xE3o implementa delete");
@@ -1565,7 +1811,7 @@ var DocumentRepository = class {
1565
1811
  };
1566
1812
 
1567
1813
  // src/use-cases/ExportConversation.use-case.ts
1568
- import { SessionNotFoundError as SessionNotFoundError4 } from "@adatechnology/meta-whatsapp-contracts";
1814
+ import { SessionNotFoundError as SessionNotFoundError5 } from "@adatechnology/meta-whatsapp-contracts";
1569
1815
  var ExportConversationUseCase = class {
1570
1816
  static {
1571
1817
  __name(this, "ExportConversationUseCase");
@@ -1576,7 +1822,7 @@ var ExportConversationUseCase = class {
1576
1822
  }
1577
1823
  async execute(params) {
1578
1824
  const result = await this.sessionRepository.exportConversation(params.companyId, params.whatsappNumber);
1579
- if (!result) throw new SessionNotFoundError4(params.whatsappNumber);
1825
+ if (!result) throw new SessionNotFoundError5(params.whatsappNumber);
1580
1826
  return result;
1581
1827
  }
1582
1828
  };
@@ -1712,6 +1958,7 @@ var FlowInterpreter = class {
1712
1958
  return this.moveTo(input, resolveNext(node, branch));
1713
1959
  }
1714
1960
  if (node.type === "action") {
1961
+ if (!node.actionKind) return this.moveTo(input, resolveNext(node, void 0));
1715
1962
  const handler = node.actionKind ? this.actionHandlers.get(node.actionKind) : void 0;
1716
1963
  if (!handler) return {
1717
1964
  kind: "terminal",
@@ -1733,7 +1980,7 @@ var FlowInterpreter = class {
1733
1980
  context: contextAfterAction
1734
1981
  }, nextNodeId2);
1735
1982
  }
1736
- const isChoice = node.type === "menu" || node.questionType === "choice";
1983
+ const isChoice = node.type === "menu" || node.type === "dynamic_choice" || node.questionType === "choice";
1737
1984
  if (input.userAnswer === void 0) {
1738
1985
  return {
1739
1986
  kind: "awaiting-answer",
@@ -1741,9 +1988,10 @@ var FlowInterpreter = class {
1741
1988
  context: input.context
1742
1989
  };
1743
1990
  }
1991
+ const storedValue = input.answerValue !== void 0 ? input.answerValue : input.userAnswer;
1744
1992
  const updatedContext = node.contextKey ? {
1745
1993
  ...input.context,
1746
- [node.contextKey]: input.userAnswer
1994
+ [node.contextKey]: storedValue
1747
1995
  } : input.context;
1748
1996
  const answerId = isChoice ? input.userAnswer : void 0;
1749
1997
  const nextNodeId = resolveNext(node, answerId);
@@ -1786,6 +2034,8 @@ var FlowInterpreter = class {
1786
2034
  const visited = [
1787
2035
  input.currentNodeId
1788
2036
  ];
2037
+ const initialNode = input.graph.nodes[input.currentNodeId];
2038
+ if (options?.enterInitialNode && initialNode) await options.onNodeEntered?.(initialNode, input.context);
1789
2039
  let current = input;
1790
2040
  let steps = 0;
1791
2041
  while (steps < maxSteps) {
@@ -1797,11 +2047,14 @@ var FlowInterpreter = class {
1797
2047
  steps
1798
2048
  };
1799
2049
  visited.push(result.nodeId);
2050
+ const enteredNode = current.graph.nodes[result.nodeId];
2051
+ if (enteredNode) await options?.onNodeEntered?.(enteredNode, result.context);
1800
2052
  current = {
1801
2053
  ...current,
1802
2054
  currentNodeId: result.nodeId,
1803
2055
  context: result.context,
1804
- userAnswer: void 0
2056
+ userAnswer: void 0,
2057
+ answerValue: void 0
1805
2058
  };
1806
2059
  }
1807
2060
  return {
@@ -1813,78 +2066,1034 @@ var FlowInterpreter = class {
1813
2066
  }
1814
2067
  };
1815
2068
 
1816
- // src/flows/createSendMediaAction.ts
1817
- function mediaTypeFor2(mimeType) {
1818
- if (mimeType.startsWith("image/")) return "image";
1819
- if (mimeType.startsWith("audio/")) return "audio";
1820
- if (mimeType.startsWith("video/")) return "video";
1821
- return "document";
2069
+ // src/flows/FlowRunner.ts
2070
+ import { ConfigMissingError, FLOW_DATE_LOCALE_PT_BR, FlowRunnerError as FlowRunnerError2, isCrossFlowTarget as isCrossFlowTarget2, crossFlowKey as crossFlowKey2, matchesFlowKeyword } from "@adatechnology/meta-whatsapp-contracts";
2071
+
2072
+ // src/flows/resolveFlowAnswer.ts
2073
+ import { matchFlowChoice, matchFlowKeywordRoute, validateFlowAnswer } from "@adatechnology/meta-whatsapp-contracts";
2074
+
2075
+ // src/flows/flowRunner.constant.ts
2076
+ var DEFAULT_START_FLOW_KEY = "main";
2077
+ var DEFAULT_MAX_INVALID_ANSWERS = 2;
2078
+ var DEFAULT_MAX_CROSS_FLOW_JUMPS = 5;
2079
+ var DEFAULT_FLOW_TEXT = {
2080
+ FALLBACK: "N\xE3o entendi. Pode responder de novo?",
2081
+ CHOICE_PROMPT: "Escolha uma op\xE7\xE3o:",
2082
+ LIST_BUTTON_LABEL: "Ver op\xE7\xF5es",
2083
+ SEE_MORE: "Ver mais",
2084
+ NON_TEXT_ANSWER: "Por aqui eu entendo s\xF3 texto. Pode escrever a resposta?",
2085
+ MORE_OPTIONS_TRUNCATED: "\u2026",
2086
+ HANDOFF: "Vou chamar uma pessoa da equipe para continuar por aqui.",
2087
+ HANDOFF_OUT_OF_HOURS: "Nossa equipe est\xE1 fora do hor\xE1rio agora. Sua mensagem ficou registrada e respondemos assim que voltarmos."
2088
+ };
2089
+ var DYNAMIC_CHOICE_MORE_ID = "__more__";
2090
+ var FLOW_RUNTIME_CONTEXT_KEY = "__flow";
2091
+
2092
+ // src/flows/resolveFlowAnswer.ts
2093
+ function isChoiceNode(node) {
2094
+ return node.type === "menu" || node.questionType === "choice";
1822
2095
  }
1823
- __name(mediaTypeFor2, "mediaTypeFor");
1824
- async function sendAttachment(params) {
1825
- const { attachment, channel, to, cache } = params;
1826
- const common = {
1827
- to,
1828
- mimeType: attachment.mimeType,
1829
- filename: attachment.filename,
1830
- caption: attachment.caption ?? void 0
2096
+ __name(isChoiceNode, "isChoiceNode");
2097
+ function keywordRoute(node, answer, isInteractiveReply) {
2098
+ if (isInteractiveReply || typeof node.next !== "object" || !node.next.byKeyword) return void 0;
2099
+ return matchFlowKeywordRoute(answer, node.next.byKeyword);
2100
+ }
2101
+ __name(keywordRoute, "keywordRoute");
2102
+ function matchOption(answer, options, isInteractiveReply) {
2103
+ if (isInteractiveReply) return options.some(([id]) => id === answer) ? answer : void 0;
2104
+ return matchFlowChoice(answer, options);
2105
+ }
2106
+ __name(matchOption, "matchOption");
2107
+ function resolveChoice(params, answer) {
2108
+ const optionId = matchOption(answer, params.node.options ?? [], params.isInteractiveReply);
2109
+ if (optionId) return {
2110
+ kind: "answer",
2111
+ userAnswer: optionId
1831
2112
  };
1832
- const cacheKey = cache ? {
1833
- flowMediaId: attachment.id,
1834
- senderKey: cache.senderKey
1835
- } : void 0;
1836
- if (cache && cacheKey) {
1837
- const knownMediaId = await cache.store.get(cacheKey);
1838
- if (knownMediaId) {
1839
- try {
1840
- return await channel.sendMedia({
1841
- ...common,
1842
- mediaId: knownMediaId
1843
- });
1844
- } catch {
1845
- await cache.store.clear(cacheKey);
1846
- }
1847
- }
1848
- }
1849
- const buffer = await params.objectStorage.getObject(attachment.uploadId);
1850
- const result = await channel.sendMedia({
1851
- ...common,
1852
- buffer
2113
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2114
+ return target ? {
2115
+ kind: "jump",
2116
+ target
2117
+ } : {
2118
+ kind: "invalid"
2119
+ };
2120
+ }
2121
+ __name(resolveChoice, "resolveChoice");
2122
+ function resolveDynamicChoice(params, answer) {
2123
+ const optionId = matchOption(answer, params.dynamicOptions ?? [], params.isInteractiveReply);
2124
+ if (optionId === DYNAMIC_CHOICE_MORE_ID) return {
2125
+ kind: "see-more"
2126
+ };
2127
+ if (optionId) return {
2128
+ kind: "answer",
2129
+ userAnswer: optionId
2130
+ };
2131
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2132
+ return target ? {
2133
+ kind: "jump",
2134
+ target
2135
+ } : {
2136
+ kind: "invalid"
2137
+ };
2138
+ }
2139
+ __name(resolveDynamicChoice, "resolveDynamicChoice");
2140
+ function resolveQuestion(params, answer) {
2141
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2142
+ if (target) return {
2143
+ kind: "jump",
2144
+ target
2145
+ };
2146
+ const result = validateFlowAnswer({
2147
+ node: params.node,
2148
+ answer,
2149
+ context: params.context,
2150
+ clock: params.clock
1853
2151
  });
1854
- if (cache && cacheKey && result.mediaId) await cache.store.set({
1855
- ...cacheKey,
1856
- mediaId: result.mediaId
2152
+ if (!result.isValid) return {
2153
+ kind: "invalid",
2154
+ rejection: result.rejection
2155
+ };
2156
+ return {
2157
+ kind: "answer",
2158
+ userAnswer: answer,
2159
+ value: result.value
2160
+ };
2161
+ }
2162
+ __name(resolveQuestion, "resolveQuestion");
2163
+ function resolveFlowAnswer(params) {
2164
+ if (params.answer === void 0) return {
2165
+ kind: "invalid"
2166
+ };
2167
+ if (params.node.type === "dynamic_choice") return resolveDynamicChoice(params, params.answer);
2168
+ if (isChoiceNode(params.node)) return resolveChoice(params, params.answer);
2169
+ return resolveQuestion(params, params.answer);
2170
+ }
2171
+ __name(resolveFlowAnswer, "resolveFlowAnswer");
2172
+
2173
+ // src/flows/FlowQuestionRenderer.ts
2174
+ import { FlowRunnerError, WHATSAPP_CHOICE_LIMIT as WHATSAPP_CHOICE_LIMIT2, interpolateFlowText } from "@adatechnology/meta-whatsapp-contracts";
2175
+
2176
+ // src/flows/buildFlowChoiceMessage.ts
2177
+ import { WHATSAPP_CHOICE_LIMIT, listInteractiveLimitViolations } from "@adatechnology/meta-whatsapp-contracts";
2178
+ function groupSections(options) {
2179
+ const sections = [];
2180
+ for (const option of options) {
2181
+ const title = option.section?.trim() || void 0;
2182
+ const existing = sections.find((section) => section.title === title);
2183
+ if (existing) existing.rows.push(option);
2184
+ else sections.push({
2185
+ title,
2186
+ rows: [
2187
+ option
2188
+ ]
2189
+ });
2190
+ }
2191
+ return sections.map((section) => ({
2192
+ ...section.title ? {
2193
+ title: section.title
2194
+ } : {},
2195
+ rows: section.rows.map((row) => ({
2196
+ id: row.id,
2197
+ title: row.title,
2198
+ ...row.description ? {
2199
+ description: row.description
2200
+ } : {}
2201
+ }))
2202
+ }));
2203
+ }
2204
+ __name(groupSections, "groupSections");
2205
+ function asNumberedText(params) {
2206
+ const lines = params.options.map((option, index2) => {
2207
+ const description = option.description ? ` \u2014 ${option.description}` : "";
2208
+ return `${index2 + 1}. ${option.title}${description}`;
1857
2209
  });
1858
- return result;
2210
+ const limit = WHATSAPP_CHOICE_LIMIT.TEXT_BODY_LENGTH;
2211
+ const full = `${params.body}
2212
+
2213
+ ${lines.join("\n")}`;
2214
+ if (Array.from(full).length <= limit) return {
2215
+ kind: "text",
2216
+ body: full
2217
+ };
2218
+ const truncated = `
2219
+ ${DEFAULT_FLOW_TEXT.MORE_OPTIONS_TRUNCATED}`;
2220
+ let body = `${params.body}
2221
+ `;
2222
+ for (const line of lines) {
2223
+ const candidate = `${body}
2224
+ ${line}`;
2225
+ if (Array.from(candidate).length + truncated.length > limit) break;
2226
+ body = candidate;
2227
+ }
2228
+ const withMarker = `${body}${truncated}`;
2229
+ return {
2230
+ kind: "text",
2231
+ body: Array.from(withMarker).slice(0, limit).join("")
2232
+ };
1859
2233
  }
1860
- __name(sendAttachment, "sendAttachment");
1861
- function createSendMediaAction(params) {
1862
- return async ({ node, session, channel }) => {
1863
- if (!session.flowKey) return;
1864
- const location = {
1865
- companyId: session.companyId,
1866
- flowKey: session.flowKey,
1867
- nodeId: node.id
2234
+ __name(asNumberedText, "asNumberedText");
2235
+ function buildFlowChoiceMessage(params) {
2236
+ const isPlain = params.options.every((option) => !option.description && !option.section);
2237
+ if (isPlain && params.options.length <= WHATSAPP_CHOICE_LIMIT.BUTTONS) {
2238
+ const buttons = {
2239
+ kind: "buttons",
2240
+ body: params.body,
2241
+ buttons: params.options.map((option) => ({
2242
+ id: option.id,
2243
+ title: option.title
2244
+ }))
1868
2245
  };
1869
- const attachments = await params.flowMediaRepository.listActive(location);
1870
- for (const attachment of attachments) {
1871
- try {
1872
- const { externalMessageId } = await sendAttachment({
1873
- attachment,
1874
- channel,
1875
- to: session.whatsappNumber,
1876
- objectStorage: params.objectStorage,
1877
- ...params.mediaIdCache ? {
1878
- cache: params.mediaIdCache
1879
- } : {}
1880
- });
1881
- await params.logMessage.execute({
1882
- companyId: session.companyId,
1883
- whatsappNumber: session.whatsappNumber,
1884
- direction: "outbound",
1885
- sender: "bot",
1886
- agentUserId: null,
1887
- type: mediaTypeFor2(attachment.mimeType),
2246
+ if (listInteractiveLimitViolations(buttons).length === 0) return {
2247
+ kind: "interactive",
2248
+ interactive: buttons
2249
+ };
2250
+ }
2251
+ const list = {
2252
+ kind: "list",
2253
+ body: params.body,
2254
+ buttonLabel: params.listButtonLabel,
2255
+ sections: groupSections(params.options)
2256
+ };
2257
+ if (listInteractiveLimitViolations(list).length === 0) return {
2258
+ kind: "interactive",
2259
+ interactive: list
2260
+ };
2261
+ return asNumberedText(params);
2262
+ }
2263
+ __name(buildFlowChoiceMessage, "buildFlowChoiceMessage");
2264
+
2265
+ // src/flows/flowRuntimeState.ts
2266
+ function runtimeOf(context) {
2267
+ const state = context[FLOW_RUNTIME_CONTEXT_KEY];
2268
+ return state !== null && typeof state === "object" ? state : {};
2269
+ }
2270
+ __name(runtimeOf, "runtimeOf");
2271
+ function withRuntime(context, state) {
2272
+ return {
2273
+ ...context,
2274
+ [FLOW_RUNTIME_CONTEXT_KEY]: state
2275
+ };
2276
+ }
2277
+ __name(withRuntime, "withRuntime");
2278
+
2279
+ // src/flows/FlowQuestionRenderer.ts
2280
+ var FlowQuestionRenderer = class {
2281
+ static {
2282
+ __name(this, "FlowQuestionRenderer");
2283
+ }
2284
+ config;
2285
+ providers = /* @__PURE__ */ new Map();
2286
+ constructor(config) {
2287
+ this.config = config;
2288
+ for (const [key, provider] of Object.entries(config.dynamicChoiceProviders ?? {})) this.providers.set(key, provider);
2289
+ }
2290
+ registerDynamicChoiceProvider(key, provider) {
2291
+ this.providers.set(key, provider);
2292
+ }
2293
+ interpolate(text2, variables) {
2294
+ return interpolateFlowText(text2, variables, this.config.formatValue ? {
2295
+ formatValue: this.config.formatValue
2296
+ } : {});
2297
+ }
2298
+ async prepare(params) {
2299
+ const { node, context } = params;
2300
+ const variables = {
2301
+ ...context,
2302
+ ...params.variables
2303
+ };
2304
+ const body = this.interpolate(node.question ?? this.config.choicePrompt ?? DEFAULT_FLOW_TEXT.CHOICE_PROMPT, variables);
2305
+ const listButtonLabel = node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL;
2306
+ if (node.type === "dynamic_choice") {
2307
+ const options = await this.loadDynamicOptions(params);
2308
+ const shown = options.map((option) => [
2309
+ option.id,
2310
+ option.title
2311
+ ]);
2312
+ const state = {
2313
+ ...runtimeOf(context),
2314
+ dynamic: {
2315
+ nodeId: node.id,
2316
+ page: params.page,
2317
+ options: shown
2318
+ }
2319
+ };
2320
+ return {
2321
+ message: buildFlowChoiceMessage({
2322
+ body,
2323
+ options,
2324
+ listButtonLabel
2325
+ }),
2326
+ context: withRuntime(context, state)
2327
+ };
2328
+ }
2329
+ if (isChoiceNode(node) && (node.options?.length ?? 0) > 0) {
2330
+ const options = (node.options ?? []).map(([id, title]) => {
2331
+ const detail = node.optionDetails?.[id];
2332
+ return {
2333
+ id,
2334
+ title: this.interpolate(title, variables),
2335
+ ...detail?.description ? {
2336
+ description: this.interpolate(detail.description, variables)
2337
+ } : {},
2338
+ ...detail?.section ? {
2339
+ section: detail.section
2340
+ } : {}
2341
+ };
2342
+ });
2343
+ return {
2344
+ message: buildFlowChoiceMessage({
2345
+ body,
2346
+ options,
2347
+ listButtonLabel
2348
+ }),
2349
+ context
2350
+ };
2351
+ }
2352
+ if (!node.question) return {
2353
+ context
2354
+ };
2355
+ return {
2356
+ message: {
2357
+ kind: "text",
2358
+ body
2359
+ },
2360
+ context
2361
+ };
2362
+ }
2363
+ async loadDynamicOptions(params) {
2364
+ const { node } = params;
2365
+ const provider = node.choiceProvider ? this.providers.get(node.choiceProvider) : void 0;
2366
+ if (!provider) throw new FlowRunnerError("provider-missing", node.choiceProvider ?? node.id);
2367
+ const pageSize = WHATSAPP_CHOICE_LIMIT2.LIST_ROWS - 1;
2368
+ const result = await provider({
2369
+ node,
2370
+ session: params.session,
2371
+ context: params.context,
2372
+ page: params.page,
2373
+ pageSize
2374
+ });
2375
+ const options = result.options.slice(0, pageSize).map((option) => ({
2376
+ id: option.id,
2377
+ title: option.title,
2378
+ ...option.description ? {
2379
+ description: option.description
2380
+ } : {}
2381
+ }));
2382
+ const seeMore = this.config.seeMoreLabel ?? DEFAULT_FLOW_TEXT.SEE_MORE;
2383
+ return result.hasMore ? [
2384
+ ...options,
2385
+ {
2386
+ id: DYNAMIC_CHOICE_MORE_ID,
2387
+ title: seeMore
2388
+ }
2389
+ ] : options;
2390
+ }
2391
+ };
2392
+
2393
+ // src/flows/readFlowInbound.ts
2394
+ function readFlowInbound(message) {
2395
+ const reply = message.interactive?.button_reply?.id ?? message.interactive?.list_reply?.id;
2396
+ if (reply !== void 0) return {
2397
+ kind: "reply",
2398
+ answer: reply
2399
+ };
2400
+ if (message.text?.body !== void 0) return {
2401
+ kind: "text",
2402
+ answer: message.text.body
2403
+ };
2404
+ if (message.button?.text !== void 0) return {
2405
+ kind: "text",
2406
+ answer: message.button.text
2407
+ };
2408
+ return {
2409
+ kind: "unsupported"
2410
+ };
2411
+ }
2412
+ __name(readFlowInbound, "readFlowInbound");
2413
+
2414
+ // src/flows/FlowRunner.ts
2415
+ function contactVariables(profileName) {
2416
+ if (!profileName) return {};
2417
+ return {
2418
+ contactName: profileName,
2419
+ contactFirstName: profileName.trim().split(/\s+/)[0] ?? profileName
2420
+ };
2421
+ }
2422
+ __name(contactVariables, "contactVariables");
2423
+ function resolveFlowTimeZone(config) {
2424
+ const businessHours = config.handoff?.businessHours;
2425
+ const timeZone = config.timeZone ?? (typeof businessHours === "object" ? businessHours.timeZone : void 0);
2426
+ if (!timeZone) throw new ConfigMissingError("features.flowRunner.timeZone");
2427
+ new Intl.DateTimeFormat("en-US", {
2428
+ timeZone
2429
+ });
2430
+ return timeZone;
2431
+ }
2432
+ __name(resolveFlowTimeZone, "resolveFlowTimeZone");
2433
+ var FlowRunner = class {
2434
+ static {
2435
+ __name(this, "FlowRunner");
2436
+ }
2437
+ dependencies;
2438
+ renderer;
2439
+ timeZone;
2440
+ // Variáveis da mensagem em curso, por sessão: é como a action `handoff` (que só recebe a sessão)
2441
+ // enxerga o nome do contato sem que ele precise ir para o contexto gravado.
2442
+ turnVariables = /* @__PURE__ */ new WeakMap();
2443
+ constructor(dependencies) {
2444
+ this.dependencies = dependencies;
2445
+ this.renderer = new FlowQuestionRenderer(dependencies.config);
2446
+ this.timeZone = resolveFlowTimeZone(dependencies.config);
2447
+ }
2448
+ registerDynamicChoiceProvider(key, provider) {
2449
+ this.renderer.registerDynamicChoiceProvider(key, provider);
2450
+ }
2451
+ /**
2452
+ * Variáveis para `{{chave}}`. As do host (`resolveVariables`, `contactName`, `contactFirstName`)
2453
+ * vencem as respostas do cliente: um `contextKey` chamado `contactName` não pode trocar o nome que
2454
+ * o sistema conhece pelo que o cliente digitou.
2455
+ */
2456
+ variablesFor(params) {
2457
+ return {
2458
+ ...params.context,
2459
+ ...this.turnVariables.get(params.session) ?? {}
2460
+ };
2461
+ }
2462
+ /** Atende uma mensagem. Um turno por conversa de cada vez (`lock`); reentrega da mesma mensagem é ignorada. */
2463
+ handle(params) {
2464
+ const key = {
2465
+ companyId: params.companyId,
2466
+ whatsappNumber: params.message.from
2467
+ };
2468
+ return this.dependencies.lock.withLock(key, () => this.handleLocked(params));
2469
+ }
2470
+ /** Abre um fluxo para a conversa sem esperar mensagem — ex.: ao devolver a conversa ao bot. */
2471
+ start(params) {
2472
+ const key = {
2473
+ companyId: params.companyId,
2474
+ whatsappNumber: params.whatsappNumber
2475
+ };
2476
+ return this.dependencies.lock.withLock(key, async () => {
2477
+ const row = await this.dependencies.sessionRepository.getContext(params.companyId, params.whatsappNumber);
2478
+ if (!row) return "no-session";
2479
+ const turn = await this.openTurn({
2480
+ companyId: params.companyId,
2481
+ session: toSessionContract(row),
2482
+ ...params.profileName ? {
2483
+ profileName: params.profileName
2484
+ } : {}
2485
+ });
2486
+ const graph = await this.loadGraph(params.companyId, params.flowKey ?? this.startFlowKey());
2487
+ if (!graph) return "no-flow";
2488
+ turn.isClaimed = true;
2489
+ return this.guard(turn, async () => {
2490
+ await this.runFrom(turn, {
2491
+ graph,
2492
+ nodeId: graph.startNodeId,
2493
+ context: {
2494
+ ...turn.session.context
2495
+ },
2496
+ enterInitialNode: true
2497
+ });
2498
+ return "handled";
2499
+ });
2500
+ });
2501
+ }
2502
+ async handleLocked(params) {
2503
+ const row = await this.dependencies.sessionRepository.getContext(params.companyId, params.message.from);
2504
+ if (!row) return "no-session";
2505
+ if (row.mode === "human") return "human-mode";
2506
+ const session = toSessionContract(row);
2507
+ if (runtimeOf(session.context).lastInboundId === params.message.id) return "duplicate";
2508
+ const turn = await this.openTurn({
2509
+ companyId: params.companyId,
2510
+ session,
2511
+ inboundId: params.message.id,
2512
+ ...params.profileName ? {
2513
+ profileName: params.profileName
2514
+ } : {}
2515
+ });
2516
+ return this.guard(turn, () => this.route(turn, readFlowInbound(params.message)));
2517
+ }
2518
+ async route(turn, inbound) {
2519
+ const globalTarget = inbound.kind === "text" ? this.globalKeywordTarget(inbound.answer) : void 0;
2520
+ if (globalTarget) return this.applyGlobalTarget(turn, globalTarget);
2521
+ const whileAwaitingHuman = this.dependencies.config.whileAwaitingHuman ?? "silent";
2522
+ if (turn.session.humanRequestedAt && !turn.session.currentNodeId && whileAwaitingHuman === "silent") {
2523
+ return "awaiting-human";
2524
+ }
2525
+ const savedFlowKey = turn.session.flowKey;
2526
+ const savedGraph = await this.loadGraph(turn.companyId, savedFlowKey ?? this.startFlowKey());
2527
+ const isStale = !savedGraph && savedFlowKey !== null && savedFlowKey !== this.startFlowKey();
2528
+ const graph = savedGraph ?? (isStale ? await this.loadGraph(turn.companyId, this.startFlowKey()) : void 0);
2529
+ if (!graph) return "no-flow";
2530
+ await this.claim(turn);
2531
+ if (isStale) await this.report(turn, savedFlowKey, turn.session.currentNodeId, "cross-flow", new FlowRunnerError2("flow-not-found", savedFlowKey));
2532
+ const node = !isStale && turn.session.currentNodeId ? graph.nodes[turn.session.currentNodeId] : void 0;
2533
+ const context = {
2534
+ ...turn.session.context
2535
+ };
2536
+ if (node) {
2537
+ await this.answerNode({
2538
+ turn,
2539
+ graph,
2540
+ node,
2541
+ context,
2542
+ inbound
2543
+ });
2544
+ return "handled";
2545
+ }
2546
+ const start = graph.nodes[graph.startNodeId];
2547
+ const target = start && inbound.kind !== "unsupported" ? this.keywordJumpAtStart(start, inbound) : void 0;
2548
+ if (target) await this.jumpTo(turn, graph, target, context);
2549
+ else await this.runFrom(turn, {
2550
+ graph,
2551
+ nodeId: graph.startNodeId,
2552
+ context,
2553
+ enterInitialNode: true
2554
+ });
2555
+ return "handled";
2556
+ }
2557
+ async guard(turn, work) {
2558
+ try {
2559
+ return await work();
2560
+ } catch (error) {
2561
+ if (!turn.isClaimed) throw error;
2562
+ await this.report(turn, turn.session.flowKey, turn.session.currentNodeId, "turn", error);
2563
+ return "handled";
2564
+ }
2565
+ }
2566
+ /** Primeira escrita do turno: grava o id da mensagem antes de qualquer efeito externo. */
2567
+ async claim(turn) {
2568
+ if (turn.isClaimed) return;
2569
+ await this.save(turn, {
2570
+ flowKey: turn.session.flowKey,
2571
+ nodeId: turn.session.currentNodeId,
2572
+ context: {
2573
+ ...turn.session.context
2574
+ }
2575
+ });
2576
+ turn.isClaimed = true;
2577
+ }
2578
+ async openTurn(params) {
2579
+ const { session, profileName } = params;
2580
+ const resolver = this.dependencies.config.resolveVariables;
2581
+ const hostVariables = resolver ? await resolver({
2582
+ session,
2583
+ ...profileName ? {
2584
+ profileName
2585
+ } : {}
2586
+ }) : {};
2587
+ const baseVariables = {
2588
+ ...contactVariables(profileName),
2589
+ ...hostVariables
2590
+ };
2591
+ this.turnVariables.set(session, baseVariables);
2592
+ return {
2593
+ companyId: params.companyId,
2594
+ session,
2595
+ baseVariables,
2596
+ ...params.inboundId ? {
2597
+ inboundId: params.inboundId
2598
+ } : {},
2599
+ isClaimed: false
2600
+ };
2601
+ }
2602
+ startFlowKey() {
2603
+ return this.dependencies.config.startFlowKey ?? DEFAULT_START_FLOW_KEY;
2604
+ }
2605
+ clock() {
2606
+ const { config } = this.dependencies;
2607
+ return {
2608
+ now: config.now?.() ?? /* @__PURE__ */ new Date(),
2609
+ locale: config.dateLocale ?? FLOW_DATE_LOCALE_PT_BR,
2610
+ timeZone: this.timeZone
2611
+ };
2612
+ }
2613
+ loadGraph(companyId, flowKey) {
2614
+ return this.dependencies.flowGraphRepository.get(companyId, flowKey);
2615
+ }
2616
+ globalKeywordTarget(answer) {
2617
+ const keywords = this.dependencies.config.globalKeywords ?? [];
2618
+ return keywords.find((entry) => matchesFlowKeyword(answer, entry.keywords))?.target;
2619
+ }
2620
+ keywordJumpAtStart(start, inbound) {
2621
+ if (inbound.kind === "unsupported") return void 0;
2622
+ const decision = resolveFlowAnswer({
2623
+ node: start,
2624
+ answer: inbound.answer,
2625
+ isInteractiveReply: inbound.kind === "reply",
2626
+ context: {},
2627
+ clock: this.clock()
2628
+ });
2629
+ return decision.kind === "jump" ? decision.target : void 0;
2630
+ }
2631
+ /**
2632
+ * Palavra global vale mesmo com a conversa aguardando atendimento. Reiniciar NÃO tira o pedido da
2633
+ * fila (`humanRequestedAt` continua): a equipe ainda responde, e o cliente pode usar o bot enquanto
2634
+ * espera; quando o fluxo terminar, o runner volta ao silêncio.
2635
+ */
2636
+ async applyGlobalTarget(turn, target) {
2637
+ const context = withRuntime({
2638
+ ...turn.session.context
2639
+ }, {});
2640
+ if (target === "handoff") {
2641
+ await this.claim(turn);
2642
+ await this.handOff(turn, context);
2643
+ return "handled";
2644
+ }
2645
+ const flowKey = target === "restart" ? this.startFlowKey() : crossFlowKey2(target);
2646
+ const graph = await this.loadGraph(turn.companyId, flowKey);
2647
+ if (!graph) return "no-flow";
2648
+ await this.claim(turn);
2649
+ await this.runFrom(turn, {
2650
+ graph,
2651
+ nodeId: graph.startNodeId,
2652
+ context,
2653
+ enterInitialNode: true
2654
+ });
2655
+ return "handled";
2656
+ }
2657
+ async answerNode(params) {
2658
+ const { turn, graph, node, context, inbound } = params;
2659
+ const runtime = runtimeOf(context);
2660
+ const dynamic = runtime.dynamic?.nodeId === node.id ? runtime.dynamic : void 0;
2661
+ const page = dynamic?.page ?? 0;
2662
+ if (inbound.kind === "unsupported") {
2663
+ const text2 = this.dependencies.config.nonTextAnswerMessage ?? DEFAULT_FLOW_TEXT.NON_TEXT_ANSWER;
2664
+ await this.say(turn, text2, context);
2665
+ return this.awaitAnswer(turn, graph, node, context, page);
2666
+ }
2667
+ const decision = resolveFlowAnswer({
2668
+ node,
2669
+ answer: inbound.answer,
2670
+ isInteractiveReply: inbound.kind === "reply",
2671
+ context,
2672
+ clock: this.clock(),
2673
+ ...dynamic ? {
2674
+ dynamicOptions: dynamic.options
2675
+ } : {}
2676
+ });
2677
+ if (decision.kind === "jump") return this.jumpTo(turn, graph, decision.target, withRuntime(context, {}));
2678
+ if (decision.kind === "see-more") return this.awaitAnswer(turn, graph, node, context, page + 1);
2679
+ if (decision.kind === "invalid" && this.followsDefaultWhenUnmatched(node)) {
2680
+ return this.runFrom(turn, {
2681
+ graph,
2682
+ nodeId: node.id,
2683
+ context: withRuntime(context, {}),
2684
+ userAnswer: inbound.answer,
2685
+ enterInitialNode: false
2686
+ });
2687
+ }
2688
+ if (decision.kind === "invalid") return this.handleInvalid(turn, graph, node, context, decision.rejection);
2689
+ await this.runFrom(turn, {
2690
+ graph,
2691
+ nodeId: node.id,
2692
+ context: withRuntime(context, {}),
2693
+ userAnswer: decision.userAnswer,
2694
+ ...decision.value !== void 0 ? {
2695
+ answerValue: decision.value
2696
+ } : {},
2697
+ enterInitialNode: false
2698
+ });
2699
+ }
2700
+ followsDefaultWhenUnmatched(node) {
2701
+ if (!isChoiceNode(node)) return false;
2702
+ return (node.unmatchedChoice ?? this.dependencies.config.unmatchedChoice ?? "reask") === "default";
2703
+ }
2704
+ async handleInvalid(turn, graph, node, context, rejection) {
2705
+ const runtime = runtimeOf(context);
2706
+ const attempts = (runtime.invalidAnswers ?? 0) + 1;
2707
+ const limit = node.maxInvalidAnswers ?? this.dependencies.config.maxInvalidAnswers ?? DEFAULT_MAX_INVALID_ANSWERS;
2708
+ if (attempts >= limit) return this.handOff(turn, withRuntime(context, {}));
2709
+ const updated = withRuntime(context, {
2710
+ ...runtime,
2711
+ invalidAnswers: attempts
2712
+ });
2713
+ await this.say(turn, this.fallbackText(node, rejection), updated);
2714
+ await this.awaitAnswer(turn, graph, node, updated, runtime.dynamic?.nodeId === node.id ? runtime.dynamic.page : 0);
2715
+ }
2716
+ fallbackText(node, rejection) {
2717
+ const { config } = this.dependencies;
2718
+ return node.fallbackMessage ?? (rejection ? config.rejectionMessages?.[rejection] : void 0) ?? config.defaultFallbackMessage ?? DEFAULT_FLOW_TEXT.FALLBACK;
2719
+ }
2720
+ async handOff(turn, context) {
2721
+ const isWithinHours = await this.dependencies.handoff.request({
2722
+ companyId: turn.companyId,
2723
+ whatsappNumber: turn.session.whatsappNumber,
2724
+ variables: {
2725
+ ...context,
2726
+ ...turn.baseVariables
2727
+ }
2728
+ });
2729
+ await this.save(turn, {
2730
+ flowKey: null,
2731
+ nodeId: null,
2732
+ context: {
2733
+ ...context,
2734
+ handoffWithinBusinessHours: isWithinHours
2735
+ }
2736
+ });
2737
+ }
2738
+ async jumpTo(turn, graph, target, context) {
2739
+ if (isCrossFlowTarget2(target)) {
2740
+ const targetGraph = await this.loadGraph(turn.companyId, crossFlowKey2(target));
2741
+ if (!targetGraph) return this.reportMissingFlow(turn, graph.key, target, context);
2742
+ return this.runFrom(turn, {
2743
+ graph: targetGraph,
2744
+ nodeId: targetGraph.startNodeId,
2745
+ context,
2746
+ enterInitialNode: true
2747
+ });
2748
+ }
2749
+ return this.runFrom(turn, {
2750
+ graph,
2751
+ nodeId: target,
2752
+ context,
2753
+ enterInitialNode: true
2754
+ });
2755
+ }
2756
+ async runFrom(turn, initial) {
2757
+ const maxJumps = this.dependencies.config.maxCrossFlowJumps ?? DEFAULT_MAX_CROSS_FLOW_JUMPS;
2758
+ let params = initial;
2759
+ for (let jump = 0; jump <= maxJumps; jump++) {
2760
+ const result = await this.dependencies.interpreter.run({
2761
+ graph: params.graph,
2762
+ currentNodeId: params.nodeId,
2763
+ ...params.userAnswer !== void 0 ? {
2764
+ userAnswer: params.userAnswer
2765
+ } : {},
2766
+ ...params.answerValue !== void 0 ? {
2767
+ answerValue: params.answerValue
2768
+ } : {},
2769
+ context: params.context,
2770
+ session: turn.session,
2771
+ channel: this.dependencies.channel
2772
+ }, {
2773
+ enterInitialNode: params.enterInitialNode,
2774
+ onNodeEntered: /* @__PURE__ */ __name(async (node, context) => {
2775
+ if (node.directMessage) await this.say(turn, node.directMessage, context);
2776
+ }, "onNodeEntered")
2777
+ });
2778
+ if (result.kind === "awaiting-answer") {
2779
+ const node = params.graph.nodes[result.nodeId];
2780
+ if (node) return this.awaitAnswer(turn, params.graph, node, result.context, 0);
2781
+ return this.save(turn, {
2782
+ flowKey: null,
2783
+ nodeId: null,
2784
+ context: result.context
2785
+ });
2786
+ }
2787
+ if (result.kind === "terminal") return this.save(turn, {
2788
+ flowKey: null,
2789
+ nodeId: null,
2790
+ context: result.context
2791
+ });
2792
+ if (result.kind === "max-steps-exceeded") {
2793
+ await this.save(turn, {
2794
+ flowKey: null,
2795
+ nodeId: null,
2796
+ context: result.context
2797
+ });
2798
+ return this.report(turn, params.graph.key, null, "max-steps", new FlowRunnerError2("cycle", result.visited.join(" -> ")));
2799
+ }
2800
+ const target = await this.loadGraph(turn.companyId, result.flowKey);
2801
+ if (!target) return this.reportMissingFlow(turn, params.graph.key, result.flowKey, result.context);
2802
+ params = {
2803
+ graph: target,
2804
+ nodeId: target.startNodeId,
2805
+ context: result.context,
2806
+ enterInitialNode: true
2807
+ };
2808
+ }
2809
+ await this.save(turn, {
2810
+ flowKey: null,
2811
+ nodeId: null,
2812
+ context: params.context
2813
+ });
2814
+ return this.report(turn, params.graph.key, null, "cross-flow", new FlowRunnerError2("too-many-jumps", params.graph.key));
2815
+ }
2816
+ /** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
2817
+ async awaitAnswer(turn, graph, node, context, page) {
2818
+ try {
2819
+ const { message, context: renderedContext } = await this.renderer.prepare({
2820
+ session: turn.session,
2821
+ variables: turn.baseVariables,
2822
+ node,
2823
+ context,
2824
+ page
2825
+ });
2826
+ await this.save(turn, {
2827
+ flowKey: graph.key,
2828
+ nodeId: node.id,
2829
+ context: renderedContext
2830
+ });
2831
+ if (message) await this.send(turn, message);
2832
+ } catch (error) {
2833
+ await this.report(turn, graph.key, node.id, "render", error);
2834
+ }
2835
+ }
2836
+ async say(turn, template, context) {
2837
+ const body = this.renderer.interpolate(template, {
2838
+ ...context,
2839
+ ...turn.baseVariables
2840
+ });
2841
+ if (body.trim().length > 0) await this.send(turn, {
2842
+ kind: "text",
2843
+ body
2844
+ });
2845
+ }
2846
+ async send(turn, message) {
2847
+ const common = {
2848
+ companyId: turn.companyId,
2849
+ whatsappNumber: turn.session.whatsappNumber,
2850
+ sender: "bot",
2851
+ startState: this.dependencies.startState
2852
+ };
2853
+ if (message.kind === "text") await this.dependencies.sendMessage.sendText({
2854
+ ...common,
2855
+ body: message.body
2856
+ });
2857
+ else await this.dependencies.sendMessage.sendInteractive({
2858
+ ...common,
2859
+ interactive: message.interactive
2860
+ });
2861
+ }
2862
+ save(turn, progress) {
2863
+ const runtime = runtimeOf(progress.context);
2864
+ const context = turn.inboundId ? withRuntime(progress.context, {
2865
+ ...runtime,
2866
+ lastInboundId: turn.inboundId
2867
+ }) : progress.context;
2868
+ return this.dependencies.sessionRepository.saveFlowProgress(turn.companyId, turn.session.whatsappNumber, {
2869
+ flowKey: progress.flowKey,
2870
+ currentNodeId: progress.nodeId,
2871
+ context
2872
+ });
2873
+ }
2874
+ async reportMissingFlow(turn, fromFlowKey, target, context) {
2875
+ await this.save(turn, {
2876
+ flowKey: null,
2877
+ nodeId: null,
2878
+ context
2879
+ });
2880
+ await this.report(turn, fromFlowKey, null, "cross-flow", new FlowRunnerError2("flow-not-found", target));
2881
+ }
2882
+ /**
2883
+ * Nunca relança: só é chamado depois de o turno ter sido gravado, e relançar faria a fila repetir
2884
+ * uma mensagem já marcada como tratada. Sem gancho, o erro é descartado (a conversa fica no último
2885
+ * ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
2886
+ */
2887
+ async report(turn, flowKey, nodeId, stage, error) {
2888
+ const details = {
2889
+ companyId: turn.companyId,
2890
+ whatsappNumber: turn.session.whatsappNumber,
2891
+ flowKey,
2892
+ nodeId,
2893
+ stage
2894
+ };
2895
+ try {
2896
+ await this.dependencies.hooks?.onFlowRunnerError?.(error, details);
2897
+ } catch {
2898
+ }
2899
+ }
2900
+ };
2901
+
2902
+ // src/flows/FlowHandoff.ts
2903
+ import { interpolateFlowText as interpolateFlowText2, isWithinBusinessHours } from "@adatechnology/meta-whatsapp-contracts";
2904
+ function readParam(node, key) {
2905
+ const value = node?.actionParams?.[key];
2906
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
2907
+ }
2908
+ __name(readParam, "readParam");
2909
+ var FlowHandoff = class {
2910
+ static {
2911
+ __name(this, "FlowHandoff");
2912
+ }
2913
+ dependencies;
2914
+ constructor(dependencies) {
2915
+ this.dependencies = dependencies;
2916
+ }
2917
+ /** Devolve se caiu dentro do horário — vai para o contexto como `handoffWithinBusinessHours`. */
2918
+ async request(params) {
2919
+ const { requestHuman, sendMessage, startState, interpolation } = this.dependencies;
2920
+ try {
2921
+ await requestHuman.execute({
2922
+ companyId: params.companyId,
2923
+ whatsappNumber: params.whatsappNumber
2924
+ });
2925
+ } catch (error) {
2926
+ await this.reportFailure(error, params);
2927
+ }
2928
+ const isWithinHours = await this.isWithinHours(params.companyId);
2929
+ const template = this.messageFor(isWithinHours, params.node);
2930
+ await sendMessage.sendText({
2931
+ companyId: params.companyId,
2932
+ whatsappNumber: params.whatsappNumber,
2933
+ body: interpolateFlowText2(template, params.variables, interpolation),
2934
+ sender: "bot",
2935
+ startState
2936
+ });
2937
+ return isWithinHours;
2938
+ }
2939
+ /**
2940
+ * Handler do `actionKind: 'handoff'`. `actionParams.message` e `actionParams.outOfHoursMessage`
2941
+ * sobrescrevem os textos do runner para aquele nó.
2942
+ */
2943
+ createActionHandler(resolveVariables) {
2944
+ return async ({ node, session, context }) => {
2945
+ const isWithinHours = await this.request({
2946
+ companyId: session.companyId,
2947
+ whatsappNumber: session.whatsappNumber,
2948
+ variables: resolveVariables({
2949
+ session,
2950
+ context
2951
+ }),
2952
+ node
2953
+ });
2954
+ return {
2955
+ context: {
2956
+ handoffWithinBusinessHours: isWithinHours
2957
+ }
2958
+ };
2959
+ };
2960
+ }
2961
+ async reportFailure(error, params) {
2962
+ try {
2963
+ await this.dependencies.hooks?.onFlowRunnerError?.(error, {
2964
+ companyId: params.companyId,
2965
+ whatsappNumber: params.whatsappNumber,
2966
+ flowKey: null,
2967
+ nodeId: params.node?.id ?? null,
2968
+ stage: "handoff"
2969
+ });
2970
+ } catch {
2971
+ }
2972
+ }
2973
+ async isWithinHours(companyId) {
2974
+ const source = this.dependencies.config.businessHours;
2975
+ const hours = typeof source === "function" ? await source(companyId) : source;
2976
+ return hours ? isWithinBusinessHours(hours, this.dependencies.now()) : true;
2977
+ }
2978
+ messageFor(isWithinHours, node) {
2979
+ const { config } = this.dependencies;
2980
+ const inHours = readParam(node, "message") ?? config.message ?? DEFAULT_FLOW_TEXT.HANDOFF;
2981
+ if (isWithinHours) return inHours;
2982
+ return readParam(node, "outOfHoursMessage") ?? config.outOfHoursMessage ?? readParam(node, "message") ?? config.message ?? DEFAULT_FLOW_TEXT.HANDOFF_OUT_OF_HOURS;
2983
+ }
2984
+ };
2985
+
2986
+ // src/flows/flowTurnLock.ts
2987
+ import { sql as sql5 } from "drizzle-orm";
2988
+ function lockName(key) {
2989
+ return `meta_whatsapp_flow:${key.companyId}:${key.whatsappNumber}`;
2990
+ }
2991
+ __name(lockName, "lockName");
2992
+ var PostgresAdvisoryFlowTurnLock = class {
2993
+ static {
2994
+ __name(this, "PostgresAdvisoryFlowTurnLock");
2995
+ }
2996
+ db;
2997
+ constructor(db) {
2998
+ this.db = db;
2999
+ }
3000
+ withLock(key, work) {
3001
+ return this.db.transaction(async (transaction) => {
3002
+ await transaction.execute(sql5`select pg_advisory_xact_lock(hashtext(${lockName(key)}))`);
3003
+ return work();
3004
+ });
3005
+ }
3006
+ };
3007
+ var InProcessFlowTurnLock = class {
3008
+ static {
3009
+ __name(this, "InProcessFlowTurnLock");
3010
+ }
3011
+ tails = /* @__PURE__ */ new Map();
3012
+ async withLock(key, work) {
3013
+ const name = lockName(key);
3014
+ const previous = this.tails.get(name) ?? Promise.resolve();
3015
+ const current = previous.catch(() => void 0).then(work);
3016
+ this.tails.set(name, current);
3017
+ try {
3018
+ return await current;
3019
+ } finally {
3020
+ if (this.tails.get(name) === current) this.tails.delete(name);
3021
+ }
3022
+ }
3023
+ };
3024
+
3025
+ // src/flows/createSendMediaAction.ts
3026
+ function mediaTypeFor2(mimeType) {
3027
+ if (mimeType.startsWith("image/")) return "image";
3028
+ if (mimeType.startsWith("audio/")) return "audio";
3029
+ if (mimeType.startsWith("video/")) return "video";
3030
+ return "document";
3031
+ }
3032
+ __name(mediaTypeFor2, "mediaTypeFor");
3033
+ async function sendAttachment(params) {
3034
+ const { attachment, channel, to, cache } = params;
3035
+ const common = {
3036
+ to,
3037
+ mimeType: attachment.mimeType,
3038
+ filename: attachment.filename,
3039
+ caption: attachment.caption ?? void 0
3040
+ };
3041
+ const cacheKey = cache ? {
3042
+ flowMediaId: attachment.id,
3043
+ senderKey: cache.senderKey
3044
+ } : void 0;
3045
+ if (cache && cacheKey) {
3046
+ const knownMediaId = await cache.store.get(cacheKey);
3047
+ if (knownMediaId) {
3048
+ try {
3049
+ return await channel.sendMedia({
3050
+ ...common,
3051
+ mediaId: knownMediaId
3052
+ });
3053
+ } catch {
3054
+ await cache.store.clear(cacheKey);
3055
+ }
3056
+ }
3057
+ }
3058
+ const buffer = await params.objectStorage.getObject(attachment.uploadId);
3059
+ const result = await channel.sendMedia({
3060
+ ...common,
3061
+ buffer
3062
+ });
3063
+ if (cache && cacheKey && result.mediaId) await cache.store.set({
3064
+ ...cacheKey,
3065
+ mediaId: result.mediaId
3066
+ });
3067
+ return result;
3068
+ }
3069
+ __name(sendAttachment, "sendAttachment");
3070
+ function createSendMediaAction(params) {
3071
+ return async ({ node, session, channel }) => {
3072
+ if (!session.flowKey) return;
3073
+ const location = {
3074
+ companyId: session.companyId,
3075
+ flowKey: session.flowKey,
3076
+ nodeId: node.id
3077
+ };
3078
+ const attachments = await params.flowMediaRepository.listActive(location);
3079
+ for (const attachment of attachments) {
3080
+ try {
3081
+ const { externalMessageId } = await sendAttachment({
3082
+ attachment,
3083
+ channel,
3084
+ to: session.whatsappNumber,
3085
+ objectStorage: params.objectStorage,
3086
+ ...params.mediaIdCache ? {
3087
+ cache: params.mediaIdCache
3088
+ } : {}
3089
+ });
3090
+ await params.logMessage.execute({
3091
+ companyId: session.companyId,
3092
+ whatsappNumber: session.whatsappNumber,
3093
+ direction: "outbound",
3094
+ sender: "bot",
3095
+ agentUserId: null,
3096
+ type: mediaTypeFor2(attachment.mimeType),
1888
3097
  content: attachment.caption ?? attachment.filename,
1889
3098
  payload: {
1890
3099
  filename: attachment.filename,
@@ -1978,7 +3187,7 @@ async function listAvailableProducts(params) {
1978
3187
  __name(listAvailableProducts, "listAvailableProducts");
1979
3188
 
1980
3189
  // src/repositories/FlowMediaRepository.ts
1981
- import { and as and5, asc as asc2, eq as eq6, sql as sql5 } from "drizzle-orm";
3190
+ import { and as and5, asc as asc2, eq as eq6, sql as sql6 } from "drizzle-orm";
1982
3191
  var FlowMediaRepository = class {
1983
3192
  static {
1984
3193
  __name(this, "FlowMediaRepository");
@@ -2030,7 +3239,7 @@ var FlowMediaRepository = class {
2030
3239
  caption: params.caption ?? null,
2031
3240
  sortOrder: params.sortOrder ?? 0,
2032
3241
  active: true,
2033
- updatedAt: sql5`now()`
3242
+ updatedAt: sql6`now()`
2034
3243
  }
2035
3244
  }).returning();
2036
3245
  return row;
@@ -2046,7 +3255,7 @@ var FlowMediaRepository = class {
2046
3255
  ...params.active !== void 0 ? {
2047
3256
  active: params.active
2048
3257
  } : {},
2049
- updatedAt: sql5`now()`
3258
+ updatedAt: sql6`now()`
2050
3259
  }).where(and5(eq6(flowMedia.companyId, params.companyId), eq6(flowMedia.id, params.id))).returning();
2051
3260
  return row;
2052
3261
  }
@@ -2060,13 +3269,13 @@ var FlowMediaRepository = class {
2060
3269
  }
2061
3270
  // Chamado ao salvar o grafo: nós apagados no editor deixam linhas que nada mais alcança.
2062
3271
  async detachRemovedNodes(params) {
2063
- const condition = params.existingNodeIds.length === 0 ? void 0 : sql5`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
3272
+ const condition = params.existingNodeIds.length === 0 ? void 0 : sql6`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
2064
3273
  await this.db.delete(flowMedia).where(and5(eq6(flowMedia.companyId, params.companyId), eq6(flowMedia.flowKey, params.flowKey), condition));
2065
3274
  }
2066
3275
  };
2067
3276
 
2068
3277
  // src/repositories/FlowMediaIdRepository.ts
2069
- import { eq as eq7, sql as sql6 } from "drizzle-orm";
3278
+ import { eq as eq7, sql as sql7 } from "drizzle-orm";
2070
3279
  var FlowMediaIdRepository = class {
2071
3280
  static {
2072
3281
  __name(this, "FlowMediaIdRepository");
@@ -2090,20 +3299,20 @@ var FlowMediaIdRepository = class {
2090
3299
  */
2091
3300
  async set(params) {
2092
3301
  await this.db.update(flowMedia).set({
2093
- metaMediaIds: sql6`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
3302
+ metaMediaIds: sql7`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
2094
3303
  }).where(eq7(flowMedia.id, params.flowMediaId));
2095
3304
  }
2096
3305
  /** Remove só a chave deste número — o id do outro número continua válido. */
2097
3306
  async clear(params) {
2098
3307
  await this.db.update(flowMedia).set({
2099
- metaMediaIds: sql6`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
3308
+ metaMediaIds: sql7`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
2100
3309
  }).where(eq7(flowMedia.id, params.flowMediaId));
2101
3310
  }
2102
3311
  };
2103
3312
 
2104
3313
  // src/channel/WhatsAppChannelAdapter.ts
2105
3314
  import { WhatsAppWindowExpiredError as ProviderWindowExpiredError } from "@adatechnology/meta-graph-core";
2106
- import { WindowExpiredError as WindowExpiredError2 } from "@adatechnology/meta-whatsapp-contracts";
3315
+ import { WindowExpiredError as WindowExpiredError2, isPreviewContact } from "@adatechnology/meta-whatsapp-contracts";
2107
3316
 
2108
3317
  // src/channel/previewMedia.ts
2109
3318
  import { PREVIEW_MEDIA_ID_PREFIX, toPreviewMediaId, resolvePreviewUploadId } from "@adatechnology/meta-whatsapp-contracts";
@@ -2115,9 +3324,16 @@ var WhatsAppChannelAdapter = class {
2115
3324
  }
2116
3325
  messages;
2117
3326
  previewMedia;
2118
- constructor(messages2, previewMedia) {
3327
+ previewContacts;
3328
+ constructor(messages2, previewMedia, previewContacts) {
2119
3329
  this.messages = messages2;
2120
3330
  this.previewMedia = previewMedia;
3331
+ this.previewContacts = previewContacts;
3332
+ }
3333
+ /** `preview.<uuid>` quando o destino é contato do simulador e o recurso está ligado. */
3334
+ previewMessageId(to) {
3335
+ if (!this.previewContacts?.isEnabled || !isPreviewContact(to)) return void 0;
3336
+ return `preview.${this.previewContacts.generateId?.() ?? globalThis.crypto.randomUUID()}`;
2121
3337
  }
2122
3338
  async translateErrors(operation) {
2123
3339
  try {
@@ -2128,12 +3344,20 @@ var WhatsAppChannelAdapter = class {
2128
3344
  }
2129
3345
  }
2130
3346
  async sendText(to, body) {
3347
+ const previewId = this.previewMessageId(to);
3348
+ if (previewId) return {
3349
+ externalMessageId: previewId
3350
+ };
2131
3351
  const result = await this.translateErrors(() => this.messages.sendText(to, body));
2132
3352
  return {
2133
3353
  externalMessageId: result.waMessageId
2134
3354
  };
2135
3355
  }
2136
3356
  async sendMedia(params) {
3357
+ const previewId = this.previewMessageId(params.to);
3358
+ if (previewId) return {
3359
+ externalMessageId: previewId
3360
+ };
2137
3361
  const result = await this.translateErrors(() => this.messages.sendMedia(params));
2138
3362
  return {
2139
3363
  externalMessageId: result.waMessageId,
@@ -2141,28 +3365,49 @@ var WhatsAppChannelAdapter = class {
2141
3365
  };
2142
3366
  }
2143
3367
  async sendTemplate(params) {
3368
+ const previewId = this.previewMessageId(params.to);
3369
+ if (previewId) return {
3370
+ externalMessageId: previewId
3371
+ };
2144
3372
  const result = await this.translateErrors(() => this.messages.sendTemplate(params));
2145
3373
  return {
2146
3374
  externalMessageId: result.waMessageId
2147
3375
  };
2148
3376
  }
2149
3377
  async sendInteractiveList(params) {
3378
+ const previewId = this.previewMessageId(params.to);
3379
+ if (previewId) return {
3380
+ externalMessageId: previewId
3381
+ };
3382
+ const sections = (params.sections ?? [
3383
+ {
3384
+ rows: params.rows ?? []
3385
+ }
3386
+ ]).map((section) => ({
3387
+ title: section.title ?? params.buttonLabel,
3388
+ rows: section.rows.map((row) => ({
3389
+ id: row.id,
3390
+ title: row.title,
3391
+ ...row.description ? {
3392
+ description: row.description
3393
+ } : {}
3394
+ }))
3395
+ }));
2150
3396
  const result = await this.translateErrors(() => this.messages.sendInteractiveList({
2151
3397
  to: params.to,
2152
3398
  bodyText: params.body,
2153
3399
  buttonText: params.buttonLabel,
2154
- sections: [
2155
- {
2156
- title: params.buttonLabel,
2157
- rows: params.rows
2158
- }
2159
- ]
3400
+ sections
2160
3401
  }));
2161
3402
  return {
2162
3403
  externalMessageId: result.waMessageId
2163
3404
  };
2164
3405
  }
2165
3406
  async sendInteractiveButtons(params) {
3407
+ const previewId = this.previewMessageId(params.to);
3408
+ if (previewId) return {
3409
+ externalMessageId: previewId
3410
+ };
2166
3411
  const result = await this.translateErrors(() => this.messages.sendInteractiveButtons({
2167
3412
  to: params.to,
2168
3413
  bodyText: params.body,
@@ -2173,6 +3418,10 @@ var WhatsAppChannelAdapter = class {
2173
3418
  };
2174
3419
  }
2175
3420
  async sendProductList(params) {
3421
+ const previewId = this.previewMessageId(params.to);
3422
+ if (previewId) return {
3423
+ externalMessageId: previewId
3424
+ };
2176
3425
  const result = await this.translateErrors(() => this.messages.sendProductListMessage({
2177
3426
  to: params.to,
2178
3427
  headerText: params.headerText,
@@ -2207,7 +3456,6 @@ var WhatsAppChannelAdapter = class {
2207
3456
 
2208
3457
  // src/channel/ReceiveWebhook.use-case.ts
2209
3458
  import { whatsAppWebhookPayloadSchema, resolveContactProfileName, whatsAppTemplateStatusUpdateSchema, whatsAppPhoneNumberQualityUpdateSchema, WHATSAPP_WEBHOOK_FIELDS } from "@adatechnology/meta-whatsapp-contracts";
2210
- import { isDeterministicMetaRejection } from "@adatechnology/meta-graph-core";
2211
3459
 
2212
3460
  // src/channel/webhookSecurity.ts
2213
3461
  import { WEBHOOK_CLAIM_TTL_SECONDS, WEBHOOK_NONCE_TTL_SECONDS, buildWebhookDeliveryKey, isValidWebhookChallenge, isValidWebhookSignature } from "@adatechnology/meta-graph-core";
@@ -2557,91 +3805,6 @@ function extractMediaDescriptor(message) {
2557
3805
  }
2558
3806
  __name(extractMediaDescriptor, "extractMediaDescriptor");
2559
3807
 
2560
- // src/channel/inboundDispatch.ts
2561
- function buildInboundJobId(job) {
2562
- return job.kind === "message" ? `wa-inbound-message:${job.message.id}` : `wa-inbound-status:${job.status.id}:${job.status.status}`;
2563
- }
2564
- __name(buildInboundJobId, "buildInboundJobId");
2565
- function toSessionContract(row) {
2566
- return {
2567
- id: row.id,
2568
- companyId: row.companyId,
2569
- whatsappNumber: row.whatsappNumber,
2570
- currentState: row.currentState,
2571
- flowKey: row.flowKey,
2572
- currentNodeId: row.currentNodeId,
2573
- context: row.context,
2574
- mode: row.mode,
2575
- assignedUserId: row.assignedUserId,
2576
- humanRequestedAt: row.humanRequestedAt?.toISOString() ?? null,
2577
- lastInboundAt: row.lastInboundAt?.toISOString() ?? null,
2578
- lastAgentReadAt: row.lastAgentReadAt?.toISOString() ?? null,
2579
- lastActivity: row.lastActivity.toISOString(),
2580
- createdAt: row.createdAt.toISOString(),
2581
- updatedAt: row.updatedAt.toISOString()
2582
- };
2583
- }
2584
- __name(toSessionContract, "toSessionContract");
2585
- function extractAnswer(message) {
2586
- const interactive = message.interactive;
2587
- if (interactive?.button_reply) return interactive.button_reply.id;
2588
- if (interactive?.list_reply) return interactive.list_reply.id;
2589
- return message.text?.body;
2590
- }
2591
- __name(extractAnswer, "extractAnswer");
2592
- var InboundEffectsDispatcher = class {
2593
- static {
2594
- __name(this, "InboundEffectsDispatcher");
2595
- }
2596
- params;
2597
- constructor(params) {
2598
- this.params = params;
2599
- }
2600
- async run(job) {
2601
- if (job.kind === "message") return this.runMessageEffects(job);
2602
- return this.runStatusEffects(job);
2603
- }
2604
- async runMessageEffects(job) {
2605
- const { companyId, message, savedMessageId, media } = job;
2606
- if (media) {
2607
- await this.params.hooks?.onMediaReceived?.({
2608
- companyId,
2609
- messageId: savedMessageId,
2610
- whatsappNumber: message.from,
2611
- sourceMediaId: media.sourceMediaId,
2612
- mimeType: media.mimeType,
2613
- ...media.filename ? {
2614
- filename: media.filename
2615
- } : {}
2616
- });
2617
- }
2618
- const sessionRow = await this.params.sessionRepository.getContext(companyId, message.from);
2619
- if (!sessionRow) return;
2620
- if (sessionRow.mode === "human") return;
2621
- const outcome = await this.params.hooks?.onMessageReceived?.(message, toSessionContract(sessionRow), job.profileName === void 0 ? {} : {
2622
- profileName: job.profileName
2623
- });
2624
- if (outcome?.outcome === "handled") return;
2625
- void extractAnswer(message);
2626
- }
2627
- async runStatusEffects(job) {
2628
- const sessionRow = await this.params.sessionRepository.getContext(job.companyId, job.whatsappNumber);
2629
- await this.params.hooks?.onStatusUpdate?.(job.status, sessionRow ? toSessionContract(sessionRow) : null);
2630
- }
2631
- };
2632
- var ProcessInboundDispatchUseCase = class {
2633
- static {
2634
- __name(this, "ProcessInboundDispatchUseCase");
2635
- }
2636
- dispatcher;
2637
- constructor(dispatcher) {
2638
- this.dispatcher = dispatcher;
2639
- }
2640
- async execute(job) {
2641
- await this.dispatcher.run(job);
2642
- }
2643
- };
2644
-
2645
3808
  // src/channel/ReceiveWebhook.use-case.ts
2646
3809
  var EMPTY_RESULT = {
2647
3810
  messagesProcessed: 0,
@@ -2706,6 +3869,9 @@ var ReceiveWebhookUseCase = class {
2706
3869
  } : {},
2707
3870
  ...params.realtime ? {
2708
3871
  realtime: params.realtime
3872
+ } : {},
3873
+ ...params.flowRunner ? {
3874
+ flowRunner: params.flowRunner
2709
3875
  } : {}
2710
3876
  });
2711
3877
  }
@@ -2891,24 +4057,15 @@ var ReceiveWebhookUseCase = class {
2891
4057
  });
2892
4058
  return;
2893
4059
  }
2894
- try {
2895
- await this.dispatcher.run(job);
2896
- } catch (error) {
2897
- if (!isDeterministicMetaRejection(error)) throw error;
2898
- await this.params.hooks?.onInboundEffectRejected?.({
2899
- companyId: job.companyId,
2900
- kind: job.kind,
2901
- whatsappNumber: resolveJobNumber(job),
2902
- code: error.code,
2903
- error
2904
- });
2905
- }
4060
+ await runInboundEffects({
4061
+ dispatcher: this.dispatcher,
4062
+ job,
4063
+ ...this.params.hooks ? {
4064
+ hooks: this.params.hooks
4065
+ } : {}
4066
+ });
2906
4067
  }
2907
4068
  };
2908
- function resolveJobNumber(job) {
2909
- return job.kind === "message" ? job.message.from : job.whatsappNumber;
2910
- }
2911
- __name(resolveJobNumber, "resolveJobNumber");
2912
4069
 
2913
4070
  // src/use-cases/resolveTranscriptionPolicy.ts
2914
4071
  function createTranscriptionPolicyResolver(dependencies) {
@@ -2971,7 +4128,9 @@ function createMetaWhatsAppModule(params) {
2971
4128
  isEnabled: true,
2972
4129
  objectStorage: providers.objectStorage
2973
4130
  } : void 0;
2974
- const channel = new WhatsAppChannelAdapter(messageProvider, previewMediaSupport);
4131
+ const channel = new WhatsAppChannelAdapter(messageProvider, previewMediaSupport, params.features?.previewContacts ? {
4132
+ isEnabled: true
4133
+ } : void 0);
2975
4134
  const sessionRepository = new SessionRepository(db);
2976
4135
  const messageRepository = new MessageRepository(db);
2977
4136
  const settingsRepository = new SettingsRepository(db);
@@ -2982,6 +4141,40 @@ function createMetaWhatsAppModule(params) {
2982
4141
  const flowMediaRepository = new FlowMediaRepository(db);
2983
4142
  const logMessage = new LogMessageUseCase(sessionRepository, messageRepository, providers.realtime, providers.moderator);
2984
4143
  const sendMessage = new SendMessageUseCase(channel, sessionRepository, logMessage, providers.objectStorage, documentRepository);
4144
+ const requestHuman = new RequestHumanConversationUseCase(sessionRepository, providers.realtime, hooks);
4145
+ const flowInterpreter = flowEngineEnabled ? new FlowInterpreter() : void 0;
4146
+ const flowRunnerFeature = params.features?.flowRunner ?? false;
4147
+ const flowRunnerConfig = flowInterpreter && flowRunnerFeature ? flowRunnerFeature === true ? {} : flowRunnerFeature : void 0;
4148
+ const flowHandoff = flowRunnerConfig ? new FlowHandoff({
4149
+ requestHuman,
4150
+ sendMessage,
4151
+ startState,
4152
+ config: flowRunnerConfig.handoff ?? {},
4153
+ now: flowRunnerConfig.now ?? (() => /* @__PURE__ */ new Date()),
4154
+ interpolation: flowRunnerConfig.formatValue ? {
4155
+ formatValue: flowRunnerConfig.formatValue
4156
+ } : {},
4157
+ ...hooks ? {
4158
+ hooks
4159
+ } : {}
4160
+ }) : void 0;
4161
+ const flowRunner = flowInterpreter && flowRunnerConfig && flowHandoff ? new FlowRunner({
4162
+ interpreter: flowInterpreter,
4163
+ flowGraphRepository,
4164
+ sessionRepository,
4165
+ sendMessage,
4166
+ channel,
4167
+ handoff: flowHandoff,
4168
+ lock: providers.flowTurnLock ?? new PostgresAdvisoryFlowTurnLock(db),
4169
+ startState,
4170
+ config: flowRunnerConfig,
4171
+ ...hooks ? {
4172
+ hooks
4173
+ } : {}
4174
+ }) : void 0;
4175
+ if (flowInterpreter && flowRunner && flowHandoff) {
4176
+ flowInterpreter.registerFlowAction(FLOW_ACTION_KIND.HANDOFF, flowHandoff.createActionHandler((turn) => flowRunner.variablesFor(turn)));
4177
+ }
2985
4178
  const receiveWebhook = new ReceiveWebhookUseCase({
2986
4179
  appSecret: config.appSecret,
2987
4180
  phoneNumberId: config.phoneNumberId,
@@ -2992,9 +4185,14 @@ function createMetaWhatsAppModule(params) {
2992
4185
  startState,
2993
4186
  hooks,
2994
4187
  realtime: providers.realtime,
2995
- redactInboundLocation: params.features?.redactInboundLocation ?? false
4188
+ ...providers.inboundQueue ? {
4189
+ inboundQueue: providers.inboundQueue
4190
+ } : {},
4191
+ redactInboundLocation: params.features?.redactInboundLocation ?? false,
4192
+ ...flowRunner ? {
4193
+ flowRunner
4194
+ } : {}
2996
4195
  });
2997
- const flowInterpreter = flowEngineEnabled ? new FlowInterpreter() : void 0;
2998
4196
  if (flowInterpreter && providers.objectStorage?.getObject) {
2999
4197
  flowInterpreter.registerFlowAction(FLOW_ACTION_KIND.SEND_MEDIA, createSendMediaAction({
3000
4198
  flowMediaRepository,
@@ -3062,8 +4260,10 @@ function createMetaWhatsAppModule(params) {
3062
4260
  conversations: {
3063
4261
  log: logMessage,
3064
4262
  send: sendMessage,
3065
- takeover: new TakeoverConversationUseCase(sessionRepository, providers.realtime),
3066
- release: new ReleaseConversationUseCase(sessionRepository, providers.realtime),
4263
+ takeover: new TakeoverConversationUseCase(sessionRepository, providers.realtime, hooks),
4264
+ release: new ReleaseConversationUseCase(sessionRepository, providers.realtime, hooks),
4265
+ // Marca o pedido de atendimento (fila "aguardando atendimento") e dispara `onHumanRequested`.
4266
+ requestHuman,
3067
4267
  list: new ListConversationsUseCase(sessionRepository),
3068
4268
  listMessages: new ListMessagesUseCase(sessionRepository, messageRepository),
3069
4269
  listDocuments,
@@ -3102,15 +4302,47 @@ function createMetaWhatsAppModule(params) {
3102
4302
  webhook: {
3103
4303
  receive: receiveWebhook,
3104
4304
  // GET de verificação da Meta — o host liga na sua rota e devolve o retorno como texto puro.
4305
+ /**
4306
+ * Comando do simulador (ponte do `conversations-ui`) → payload da Meta com o `phone_number_id`
4307
+ * DESTE módulo. Montar com o padrão do builder fazia o filtro de número descartar a entrega.
4308
+ * Quem assina e entrega em `receive` é a rota do host.
4309
+ */
4310
+ buildPreviewPayload: /* @__PURE__ */ __name((command, envelope) => buildPreviewInboundPayload(command, {
4311
+ ...config.wabaId ? {
4312
+ wabaId: config.wabaId
4313
+ } : {},
4314
+ ...envelope,
4315
+ phoneNumberId: config.phoneNumberId
4316
+ }), "buildPreviewPayload"),
3105
4317
  verifyChallenge: /* @__PURE__ */ __name((query) => verifyWebhookChallenge({
3106
4318
  ...query,
3107
4319
  expectedToken: config.webhookVerifyToken
3108
- }), "verifyChallenge")
4320
+ }), "verifyChallenge"),
4321
+ // Lado do worker de `providers.inboundQueue`: roda os efeitos de um job já enfileirado. Existe
4322
+ // mesmo sem fila configurada — um worker de outra instância pode consumir a fila desta.
4323
+ processInboundDispatch: new ProcessInboundDispatchUseCase(new InboundEffectsDispatcher({
4324
+ sessionRepository,
4325
+ ...hooks ? {
4326
+ hooks
4327
+ } : {},
4328
+ ...providers.realtime ? {
4329
+ realtime: providers.realtime
4330
+ } : {},
4331
+ ...flowRunner ? {
4332
+ flowRunner
4333
+ } : {}
4334
+ }), hooks)
3109
4335
  },
3110
4336
  // undefined quando features.flowEngine === false.
3111
4337
  flows: flowInterpreter ? {
3112
4338
  interpreter: flowInterpreter,
3113
4339
  registerFlowAction: /* @__PURE__ */ __name((kind, handler) => flowInterpreter.registerFlowAction(kind, handler), "registerFlowAction"),
4340
+ // undefined quando `features.flowRunner` está desligado — o host dirige a conversa.
4341
+ runner: flowRunner,
4342
+ registerDynamicChoiceProvider: /* @__PURE__ */ __name((key, provider) => {
4343
+ if (!flowRunner) throw new ConfigMissingError2("features.flowRunner");
4344
+ flowRunner.registerDynamicChoiceProvider(key, provider);
4345
+ }, "registerDynamicChoiceProvider"),
3114
4346
  get: new GetFlowGraphUseCase(flowGraphRepository),
3115
4347
  list: new ListFlowGraphsUseCase(flowGraphRepository),
3116
4348
  create: new CreateFlowGraphUseCase(flowGraphRepository),
@@ -3131,15 +4363,29 @@ __name(createMetaWhatsAppModule, "createMetaWhatsAppModule");
3131
4363
  // src/runMigrations.ts
3132
4364
  import { join } from "path";
3133
4365
  var META_WHATSAPP_MIGRATIONS_TABLE = "meta_whatsapp_migrations";
3134
- function metaWhatsAppMigrationsFolder() {
3135
- return join(__dirname, "migrations");
4366
+ var LAYOUT_DIRECTORY = {
4367
+ v1: "migrations",
4368
+ journal: "migrations-journal"
4369
+ };
4370
+ function metaWhatsAppMigrationsFolder(params = {}) {
4371
+ return join(__dirname, LAYOUT_DIRECTORY[params.layout ?? "v1"]);
3136
4372
  }
3137
4373
  __name(metaWhatsAppMigrationsFolder, "metaWhatsAppMigrationsFolder");
4374
+ var MISSING_JOURNAL_REFUSAL = "meta/_journal.json";
3138
4375
  async function runMetaWhatsAppMigrations(params) {
3139
- await params.migrate(params.db, {
3140
- migrationsFolder: metaWhatsAppMigrationsFolder(),
4376
+ const run = /* @__PURE__ */ __name((layout) => params.migrate(params.db, {
4377
+ migrationsFolder: metaWhatsAppMigrationsFolder({
4378
+ layout
4379
+ }),
3141
4380
  migrationsTable: META_WHATSAPP_MIGRATIONS_TABLE
3142
- });
4381
+ }), "run");
4382
+ if (params.layout) return run(params.layout);
4383
+ try {
4384
+ await run("v1");
4385
+ } catch (error) {
4386
+ if (!(error instanceof Error) || !error.message.includes(MISSING_JOURNAL_REFUSAL)) throw error;
4387
+ await run("journal");
4388
+ }
3143
4389
  }
3144
4390
  __name(runMetaWhatsAppMigrations, "runMetaWhatsAppMigrations");
3145
4391
 
@@ -3221,19 +4467,28 @@ __name(redeemSseTicket, "redeemSseTicket");
3221
4467
  export {
3222
4468
  CountInboundLocationsUseCase,
3223
4469
  CreateFlowGraphUseCase,
4470
+ DEFAULT_FALLBACK_LIST_LABEL,
3224
4471
  DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
4472
+ DEFAULT_FLOW_TEXT,
4473
+ DEFAULT_MAX_INVALID_ANSWERS,
4474
+ DEFAULT_START_FLOW_KEY,
4475
+ DYNAMIC_CHOICE_MORE_ID,
3225
4476
  DeleteConversationUseCase,
3226
4477
  DeleteFlowGraphUseCase,
3227
4478
  DocumentRepository,
3228
4479
  ExportConversationUseCase,
4480
+ FLOW_RUNTIME_CONTEXT_KEY,
3229
4481
  FlowGraphCache,
3230
4482
  FlowGraphRepository,
4483
+ FlowHandoff,
3231
4484
  FlowInterpreter,
3232
4485
  FlowMediaIdRepository,
3233
4486
  FlowMediaRepository,
4487
+ FlowRunner,
3234
4488
  GetFlowGraphUseCase,
3235
4489
  GetLiveFlowPositionsUseCase,
3236
4490
  INBOUND_LOCATION_CONTENT,
4491
+ InProcessFlowTurnLock,
3237
4492
  InboundEffectsDispatcher,
3238
4493
  IngestInboundMediaUseCase,
3239
4494
  InvalidFlowGraphError,
@@ -3248,11 +4503,13 @@ export {
3248
4503
  OptimisticLockError,
3249
4504
  PREVIEW_MEDIA_ID_PREFIX,
3250
4505
  PRODUCT_LIST_LIMIT,
4506
+ PostgresAdvisoryFlowTurnLock,
3251
4507
  ProcessInboundDispatchUseCase,
3252
4508
  PurgeExpiredDocumentsUseCase,
3253
4509
  ReceiveWebhookUseCase,
3254
4510
  RedactInboundLocationsUseCase,
3255
4511
  ReleaseConversationUseCase,
4512
+ RequestHumanConversationUseCase,
3256
4513
  SaveFlowGraphUseCase,
3257
4514
  SendMessageUseCase,
3258
4515
  SessionRepository,
@@ -3266,6 +4523,7 @@ export {
3266
4523
  WEBHOOK_CLAIM_TTL_SECONDS,
3267
4524
  WEBHOOK_NONCE_TTL_SECONDS,
3268
4525
  WhatsAppChannelAdapter,
4526
+ buildFlowChoiceMessage,
3269
4527
  buildInboundJobId,
3270
4528
  claimWebhookDelivery,
3271
4529
  confirmWebhookDelivery,
@@ -3278,14 +4536,18 @@ export {
3278
4536
  flowGraphs,
3279
4537
  flowMedia,
3280
4538
  isAudioMimeType,
4539
+ isChoiceNode,
3281
4540
  isRetriableTranscriptionError,
3282
4541
  isUnsupportedTranscriptionError,
3283
4542
  issueSseTicket,
3284
4543
  messages,
3285
4544
  metaWhatsAppMigrationsFolder,
3286
4545
  metaWhatsAppSchema,
4546
+ readFlowInbound,
3287
4547
  redeemSseTicket,
3288
4548
  resolveFailureStatus,
4549
+ resolveFlowAnswer,
4550
+ resolveFlowTimeZone,
3289
4551
  resolvePreviewUploadId,
3290
4552
  runMetaWhatsAppMigrations,
3291
4553
  sessions,