@adatechnology/meta-whatsapp-module 0.9.0 → 0.11.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).
@@ -525,7 +541,7 @@ var SessionRepository = class {
525
541
  };
526
542
 
527
543
  // src/repositories/MessageRepository.ts
528
- import { and as and2, count, eq as eq2, lt, sql as sql3 } from "drizzle-orm";
544
+ import { and as and2, count, desc as desc2, eq as eq2, lt, sql as sql3 } from "drizzle-orm";
529
545
 
530
546
  // src/inboundLocation.constant.ts
531
547
  var INBOUND_LOCATION_CONTENT = "\u{1F4CD} Localiza\xE7\xE3o";
@@ -704,7 +720,8 @@ var MessageRepository = class {
704
720
  eq2(messages.sessionId, params.sessionId)
705
721
  ];
706
722
  if (params.before) conditions.push(lt(messages.createdAt, new Date(params.before)));
707
- return this.db.select().from(messages).where(and2(...conditions)).orderBy(messages.createdAt).limit(params.limit ?? DEFAULT_LIMIT2);
723
+ const newestFirst = await this.db.select().from(messages).where(and2(...conditions)).orderBy(desc2(messages.createdAt), desc2(messages.id)).limit(params.limit ?? DEFAULT_LIMIT2);
724
+ return newestFirst.reverse();
708
725
  }
709
726
  };
710
727
 
@@ -987,6 +1004,7 @@ var LogMessageUseCase = class {
987
1004
  await this.sessionRepository.touchInbound(params.companyId, params.whatsappNumber);
988
1005
  }
989
1006
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "message", {
1007
+ companyId: params.companyId,
990
1008
  direction: params.direction,
991
1009
  sender: params.sender
992
1010
  });
@@ -1205,6 +1223,7 @@ var TakeoverConversationUseCase = class {
1205
1223
  async execute(params) {
1206
1224
  await this.sessionRepository.takeover(params.companyId, params.whatsappNumber, params.agentUserId);
1207
1225
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "mode-changed", {
1226
+ companyId: params.companyId,
1208
1227
  mode: "human",
1209
1228
  assignedUserId: params.agentUserId
1210
1229
  });
@@ -1237,6 +1256,7 @@ var ReleaseConversationUseCase = class {
1237
1256
  async execute(params) {
1238
1257
  await this.sessionRepository.release(params.companyId, params.whatsappNumber);
1239
1258
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "mode-changed", {
1259
+ companyId: params.companyId,
1240
1260
  mode: "bot",
1241
1261
  assignedUserId: null
1242
1262
  });
@@ -1282,13 +1302,6 @@ function toSessionContract(row) {
1282
1302
  };
1283
1303
  }
1284
1304
  __name(toSessionContract, "toSessionContract");
1285
- function extractAnswer(message) {
1286
- const interactive = message.interactive;
1287
- if (interactive?.button_reply) return interactive.button_reply.id;
1288
- if (interactive?.list_reply) return interactive.list_reply.id;
1289
- return message.text?.body;
1290
- }
1291
- __name(extractAnswer, "extractAnswer");
1292
1305
  var InboundEffectsDispatcher = class {
1293
1306
  static {
1294
1307
  __name(this, "InboundEffectsDispatcher");
@@ -1322,7 +1335,13 @@ var InboundEffectsDispatcher = class {
1322
1335
  profileName: job.profileName
1323
1336
  });
1324
1337
  if (outcome?.outcome === "handled") return;
1325
- void extractAnswer(message);
1338
+ await this.params.flowRunner?.handle({
1339
+ companyId,
1340
+ message,
1341
+ ...job.profileName === void 0 ? {} : {
1342
+ profileName: job.profileName
1343
+ }
1344
+ });
1326
1345
  }
1327
1346
  async runStatusEffects(job) {
1328
1347
  const sessionRow = await this.params.sessionRepository.getContext(job.companyId, job.whatsappNumber);
@@ -1384,6 +1403,7 @@ var RequestHumanConversationUseCase = class {
1384
1403
  const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
1385
1404
  if (!session) throw new SessionNotFoundError(params.whatsappNumber);
1386
1405
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "human-requested", {
1406
+ companyId: params.companyId,
1387
1407
  humanRequestedAt: session.humanRequestedAt?.toISOString() ?? null
1388
1408
  });
1389
1409
  this.realtime?.emit("global", "data-changed", {});
@@ -1648,7 +1668,7 @@ var RedactInboundLocationsUseCase = class {
1648
1668
  };
1649
1669
 
1650
1670
  // src/repositories/DocumentRepository.ts
1651
- import { and as and4, asc, count as count2, desc as desc2, eq as eq5, ilike, inArray, lt as lt2, or } from "drizzle-orm";
1671
+ import { and as and4, asc, count as count2, desc as desc3, eq as eq5, ilike, inArray, lt as lt2, or } from "drizzle-orm";
1652
1672
  var DEFAULT_LIMIT3 = 50;
1653
1673
  function companyDocumentSearch(search) {
1654
1674
  const term = search?.trim();
@@ -1703,7 +1723,7 @@ var DocumentRepository = class {
1703
1723
  const where = and4(...filters);
1704
1724
  const limit = params.limit ?? DEFAULT_LIMIT3;
1705
1725
  const page = params.page && params.page > 0 ? params.page : 1;
1706
- const orderBy = params.sortDirection === "asc" ? asc(documents.linkedAt) : desc2(documents.linkedAt);
1726
+ const orderBy = params.sortDirection === "asc" ? asc(documents.linkedAt) : desc3(documents.linkedAt);
1707
1727
  const [rows, counted] = await Promise.all([
1708
1728
  this.db.select().from(documents).where(where).orderBy(orderBy).limit(limit).offset((page - 1) * limit),
1709
1729
  this.db.select({
@@ -1740,7 +1760,7 @@ var DocumentRepository = class {
1740
1760
  const where = and4(...filters);
1741
1761
  const limit = params.limit ?? DEFAULT_LIMIT3;
1742
1762
  const page = params.page && params.page > 0 ? params.page : 1;
1743
- const orderBy = params.sortDirection === "asc" ? asc(documents.linkedAt) : desc2(documents.linkedAt);
1763
+ const orderBy = params.sortDirection === "asc" ? asc(documents.linkedAt) : desc3(documents.linkedAt);
1744
1764
  const [rows, counted] = await Promise.all([
1745
1765
  this.db.select({
1746
1766
  id: documents.id,
@@ -1943,6 +1963,7 @@ var FlowInterpreter = class {
1943
1963
  return this.moveTo(input, resolveNext(node, branch));
1944
1964
  }
1945
1965
  if (node.type === "action") {
1966
+ if (!node.actionKind) return this.moveTo(input, resolveNext(node, void 0));
1946
1967
  const handler = node.actionKind ? this.actionHandlers.get(node.actionKind) : void 0;
1947
1968
  if (!handler) return {
1948
1969
  kind: "terminal",
@@ -1964,7 +1985,7 @@ var FlowInterpreter = class {
1964
1985
  context: contextAfterAction
1965
1986
  }, nextNodeId2);
1966
1987
  }
1967
- const isChoice = node.type === "menu" || node.questionType === "choice";
1988
+ const isChoice = node.type === "menu" || node.type === "dynamic_choice" || node.questionType === "choice";
1968
1989
  if (input.userAnswer === void 0) {
1969
1990
  return {
1970
1991
  kind: "awaiting-answer",
@@ -1972,9 +1993,10 @@ var FlowInterpreter = class {
1972
1993
  context: input.context
1973
1994
  };
1974
1995
  }
1996
+ const storedValue = input.answerValue !== void 0 ? input.answerValue : input.userAnswer;
1975
1997
  const updatedContext = node.contextKey ? {
1976
1998
  ...input.context,
1977
- [node.contextKey]: input.userAnswer
1999
+ [node.contextKey]: storedValue
1978
2000
  } : input.context;
1979
2001
  const answerId = isChoice ? input.userAnswer : void 0;
1980
2002
  const nextNodeId = resolveNext(node, answerId);
@@ -2017,6 +2039,8 @@ var FlowInterpreter = class {
2017
2039
  const visited = [
2018
2040
  input.currentNodeId
2019
2041
  ];
2042
+ const initialNode = input.graph.nodes[input.currentNodeId];
2043
+ if (options?.enterInitialNode && initialNode) await options.onNodeEntered?.(initialNode, input.context);
2020
2044
  let current = input;
2021
2045
  let steps = 0;
2022
2046
  while (steps < maxSteps) {
@@ -2028,11 +2052,14 @@ var FlowInterpreter = class {
2028
2052
  steps
2029
2053
  };
2030
2054
  visited.push(result.nodeId);
2055
+ const enteredNode = current.graph.nodes[result.nodeId];
2056
+ if (enteredNode) await options?.onNodeEntered?.(enteredNode, result.context);
2031
2057
  current = {
2032
2058
  ...current,
2033
2059
  currentNodeId: result.nodeId,
2034
2060
  context: result.context,
2035
- userAnswer: void 0
2061
+ userAnswer: void 0,
2062
+ answerValue: void 0
2036
2063
  };
2037
2064
  }
2038
2065
  return {
@@ -2044,6 +2071,1120 @@ var FlowInterpreter = class {
2044
2071
  }
2045
2072
  };
2046
2073
 
2074
+ // src/flows/FlowRunner.ts
2075
+ import { ConfigMissingError, FLOW_DATE_LOCALE_PT_BR, FlowRunnerError as FlowRunnerError2, isCrossFlowTarget as isCrossFlowTarget2, crossFlowKey as crossFlowKey2 } from "@adatechnology/meta-whatsapp-contracts";
2076
+
2077
+ // src/flows/resolveFlowAnswer.ts
2078
+ import { matchFlowChoice, matchFlowKeywordRoute, validateFlowAnswer } from "@adatechnology/meta-whatsapp-contracts";
2079
+
2080
+ // src/flows/flowRunner.constant.ts
2081
+ var DEFAULT_START_FLOW_KEY = "main";
2082
+ var DEFAULT_MAX_INVALID_ANSWERS = 2;
2083
+ var DEFAULT_MAX_CROSS_FLOW_JUMPS = 5;
2084
+ var DEFAULT_FLOW_TEXT = {
2085
+ FALLBACK: "N\xE3o entendi. Pode responder de novo?",
2086
+ CHOICE_PROMPT: "Escolha uma op\xE7\xE3o:",
2087
+ LIST_BUTTON_LABEL: "Ver op\xE7\xF5es",
2088
+ SEE_MORE: "Ver mais",
2089
+ NON_TEXT_ANSWER: "Por aqui eu entendo s\xF3 texto. Pode escrever a resposta?",
2090
+ MORE_OPTIONS_TRUNCATED: "\u2026",
2091
+ HANDOFF: "Vou chamar uma pessoa da equipe para continuar por aqui.",
2092
+ HANDOFF_OUT_OF_HOURS: "Nossa equipe est\xE1 fora do hor\xE1rio agora. Sua mensagem ficou registrada e respondemos assim que voltarmos."
2093
+ };
2094
+ var DYNAMIC_CHOICE_MORE_ID = "__more__";
2095
+ var FLOW_RUNTIME_CONTEXT_KEY = "__flow";
2096
+
2097
+ // src/flows/resolveFlowAnswer.ts
2098
+ function isChoiceNode(node) {
2099
+ return node.type === "menu" || node.questionType === "choice";
2100
+ }
2101
+ __name(isChoiceNode, "isChoiceNode");
2102
+ function keywordRoute(node, answer, isInteractiveReply) {
2103
+ if (isInteractiveReply || typeof node.next !== "object" || !node.next.byKeyword) return void 0;
2104
+ return matchFlowKeywordRoute(answer, node.next.byKeyword);
2105
+ }
2106
+ __name(keywordRoute, "keywordRoute");
2107
+ function matchOption(answer, options, isInteractiveReply) {
2108
+ if (isInteractiveReply) return options.some(([id]) => id === answer) ? answer : void 0;
2109
+ return matchFlowChoice(answer, options);
2110
+ }
2111
+ __name(matchOption, "matchOption");
2112
+ function resolveChoice(params, answer) {
2113
+ const optionId = matchOption(answer, params.options ?? params.node.options ?? [], params.isInteractiveReply);
2114
+ if (optionId) return {
2115
+ kind: "answer",
2116
+ userAnswer: optionId
2117
+ };
2118
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2119
+ return target ? {
2120
+ kind: "jump",
2121
+ target
2122
+ } : {
2123
+ kind: "invalid"
2124
+ };
2125
+ }
2126
+ __name(resolveChoice, "resolveChoice");
2127
+ function resolveDynamicChoice(params, answer) {
2128
+ const optionId = matchOption(answer, params.dynamicOptions ?? [], params.isInteractiveReply);
2129
+ if (optionId === DYNAMIC_CHOICE_MORE_ID) return {
2130
+ kind: "see-more"
2131
+ };
2132
+ if (optionId) return {
2133
+ kind: "answer",
2134
+ userAnswer: optionId
2135
+ };
2136
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2137
+ return target ? {
2138
+ kind: "jump",
2139
+ target
2140
+ } : {
2141
+ kind: "invalid"
2142
+ };
2143
+ }
2144
+ __name(resolveDynamicChoice, "resolveDynamicChoice");
2145
+ function resolveQuestion(params, answer) {
2146
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2147
+ if (target) return {
2148
+ kind: "jump",
2149
+ target
2150
+ };
2151
+ const result = validateFlowAnswer({
2152
+ node: params.node,
2153
+ answer,
2154
+ context: params.context,
2155
+ clock: params.clock
2156
+ });
2157
+ if (!result.isValid) return {
2158
+ kind: "invalid",
2159
+ rejection: result.rejection
2160
+ };
2161
+ return {
2162
+ kind: "answer",
2163
+ userAnswer: answer,
2164
+ value: result.value
2165
+ };
2166
+ }
2167
+ __name(resolveQuestion, "resolveQuestion");
2168
+ function resolveFlowAnswer(params) {
2169
+ if (params.answer === void 0) return {
2170
+ kind: "invalid"
2171
+ };
2172
+ if (params.node.type === "dynamic_choice") return resolveDynamicChoice(params, params.answer);
2173
+ if (isChoiceNode(params.node)) return resolveChoice(params, params.answer);
2174
+ return resolveQuestion(params, params.answer);
2175
+ }
2176
+ __name(resolveFlowAnswer, "resolveFlowAnswer");
2177
+
2178
+ // src/flows/FlowQuestionRenderer.ts
2179
+ import { FlowRunnerError, WHATSAPP_CHOICE_LIMIT as WHATSAPP_CHOICE_LIMIT2, interpolateFlowText } from "@adatechnology/meta-whatsapp-contracts";
2180
+
2181
+ // src/flows/buildFlowChoiceMessage.ts
2182
+ import { WHATSAPP_CHOICE_LIMIT, listInteractiveLimitViolations } from "@adatechnology/meta-whatsapp-contracts";
2183
+ function groupSections(options) {
2184
+ const sections = [];
2185
+ for (const option of options) {
2186
+ const title = option.section?.trim() || void 0;
2187
+ const existing = sections.find((section) => section.title === title);
2188
+ if (existing) existing.rows.push(option);
2189
+ else sections.push({
2190
+ title,
2191
+ rows: [
2192
+ option
2193
+ ]
2194
+ });
2195
+ }
2196
+ return sections.map((section) => ({
2197
+ ...section.title ? {
2198
+ title: section.title
2199
+ } : {},
2200
+ rows: section.rows.map((row) => ({
2201
+ id: row.id,
2202
+ title: row.title,
2203
+ ...row.description ? {
2204
+ description: row.description
2205
+ } : {}
2206
+ }))
2207
+ }));
2208
+ }
2209
+ __name(groupSections, "groupSections");
2210
+ function asNumberedText(params) {
2211
+ const lines = params.options.map((option, index2) => {
2212
+ const description = option.description ? ` \u2014 ${option.description}` : "";
2213
+ return `${index2 + 1}. ${option.title}${description}`;
2214
+ });
2215
+ const limit = WHATSAPP_CHOICE_LIMIT.TEXT_BODY_LENGTH;
2216
+ const full = `${params.body}
2217
+
2218
+ ${lines.join("\n")}`;
2219
+ if (Array.from(full).length <= limit) return {
2220
+ kind: "text",
2221
+ body: full
2222
+ };
2223
+ const truncated = `
2224
+ ${DEFAULT_FLOW_TEXT.MORE_OPTIONS_TRUNCATED}`;
2225
+ let body = `${params.body}
2226
+ `;
2227
+ for (const line of lines) {
2228
+ const candidate = `${body}
2229
+ ${line}`;
2230
+ if (Array.from(candidate).length + truncated.length > limit) break;
2231
+ body = candidate;
2232
+ }
2233
+ const withMarker = `${body}${truncated}`;
2234
+ return {
2235
+ kind: "text",
2236
+ body: Array.from(withMarker).slice(0, limit).join("")
2237
+ };
2238
+ }
2239
+ __name(asNumberedText, "asNumberedText");
2240
+ function buildFlowChoiceMessage(params) {
2241
+ const isPlain = params.options.every((option) => !option.description && !option.section);
2242
+ if (isPlain && params.options.length <= WHATSAPP_CHOICE_LIMIT.BUTTONS) {
2243
+ const buttons = {
2244
+ kind: "buttons",
2245
+ body: params.body,
2246
+ buttons: params.options.map((option) => ({
2247
+ id: option.id,
2248
+ title: option.title
2249
+ }))
2250
+ };
2251
+ if (listInteractiveLimitViolations(buttons).length === 0) return {
2252
+ kind: "interactive",
2253
+ interactive: buttons
2254
+ };
2255
+ }
2256
+ const list = {
2257
+ kind: "list",
2258
+ body: params.body,
2259
+ buttonLabel: params.listButtonLabel,
2260
+ sections: groupSections(params.options)
2261
+ };
2262
+ if (listInteractiveLimitViolations(list).length === 0) return {
2263
+ kind: "interactive",
2264
+ interactive: list
2265
+ };
2266
+ return asNumberedText(params);
2267
+ }
2268
+ __name(buildFlowChoiceMessage, "buildFlowChoiceMessage");
2269
+
2270
+ // src/flows/flowRuntimeState.ts
2271
+ function runtimeOf(context) {
2272
+ const state = context[FLOW_RUNTIME_CONTEXT_KEY];
2273
+ return state !== null && typeof state === "object" ? state : {};
2274
+ }
2275
+ __name(runtimeOf, "runtimeOf");
2276
+ function withRuntime(context, state) {
2277
+ return {
2278
+ ...context,
2279
+ [FLOW_RUNTIME_CONTEXT_KEY]: state
2280
+ };
2281
+ }
2282
+ __name(withRuntime, "withRuntime");
2283
+
2284
+ // src/flows/FlowQuestionRenderer.ts
2285
+ var FlowQuestionRenderer = class {
2286
+ static {
2287
+ __name(this, "FlowQuestionRenderer");
2288
+ }
2289
+ config;
2290
+ providers = /* @__PURE__ */ new Map();
2291
+ constructor(config) {
2292
+ this.config = config;
2293
+ for (const [key, provider] of Object.entries(config.dynamicChoiceProviders ?? {})) this.providers.set(key, provider);
2294
+ }
2295
+ registerDynamicChoiceProvider(key, provider) {
2296
+ this.providers.set(key, provider);
2297
+ }
2298
+ interpolate(text2, variables) {
2299
+ return interpolateFlowText(text2, variables, this.config.formatValue ? {
2300
+ formatValue: this.config.formatValue
2301
+ } : {});
2302
+ }
2303
+ async prepare(params) {
2304
+ const { node, context } = params;
2305
+ const variables = {
2306
+ ...context,
2307
+ ...params.variables
2308
+ };
2309
+ const body = this.interpolate(node.question ?? this.config.choicePrompt ?? DEFAULT_FLOW_TEXT.CHOICE_PROMPT, variables);
2310
+ const listButtonLabel = node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL;
2311
+ if (node.type === "dynamic_choice") {
2312
+ const options = await this.loadDynamicOptions(params);
2313
+ const shown = options.map((option) => [
2314
+ option.id,
2315
+ option.title
2316
+ ]);
2317
+ const state = {
2318
+ ...runtimeOf(context),
2319
+ dynamic: {
2320
+ nodeId: node.id,
2321
+ page: params.page,
2322
+ options: shown
2323
+ }
2324
+ };
2325
+ return {
2326
+ message: buildFlowChoiceMessage({
2327
+ body,
2328
+ options,
2329
+ listButtonLabel
2330
+ }),
2331
+ context: withRuntime(context, state)
2332
+ };
2333
+ }
2334
+ if (isChoiceNode(node) && (node.options?.length ?? 0) > 0) {
2335
+ const options = (node.options ?? []).map(([id, title]) => {
2336
+ const detail = node.optionDetails?.[id];
2337
+ return {
2338
+ id,
2339
+ title: this.interpolate(title, variables),
2340
+ ...detail?.description ? {
2341
+ description: this.interpolate(detail.description, variables)
2342
+ } : {},
2343
+ ...detail?.section ? {
2344
+ section: detail.section
2345
+ } : {}
2346
+ };
2347
+ });
2348
+ return {
2349
+ message: buildFlowChoiceMessage({
2350
+ body,
2351
+ options,
2352
+ listButtonLabel
2353
+ }),
2354
+ context
2355
+ };
2356
+ }
2357
+ if (!node.question) return {
2358
+ context
2359
+ };
2360
+ return {
2361
+ message: {
2362
+ kind: "text",
2363
+ body
2364
+ },
2365
+ context
2366
+ };
2367
+ }
2368
+ async loadDynamicOptions(params) {
2369
+ const { node } = params;
2370
+ const provider = node.choiceProvider ? this.providers.get(node.choiceProvider) : void 0;
2371
+ if (!provider) throw new FlowRunnerError("provider-missing", node.choiceProvider ?? node.id);
2372
+ const pageSize = WHATSAPP_CHOICE_LIMIT2.LIST_ROWS - 1;
2373
+ const result = await provider({
2374
+ node,
2375
+ session: params.session,
2376
+ context: params.context,
2377
+ page: params.page,
2378
+ pageSize
2379
+ });
2380
+ const options = result.options.slice(0, pageSize).map((option) => ({
2381
+ id: option.id,
2382
+ title: option.title,
2383
+ ...option.description ? {
2384
+ description: option.description
2385
+ } : {}
2386
+ }));
2387
+ const seeMore = this.config.seeMoreLabel ?? DEFAULT_FLOW_TEXT.SEE_MORE;
2388
+ return result.hasMore ? [
2389
+ ...options,
2390
+ {
2391
+ id: DYNAMIC_CHOICE_MORE_ID,
2392
+ title: seeMore
2393
+ }
2394
+ ] : options;
2395
+ }
2396
+ };
2397
+
2398
+ // src/flows/readFlowInbound.ts
2399
+ function readFlowInbound(message) {
2400
+ const reply = message.interactive?.button_reply?.id ?? message.interactive?.list_reply?.id;
2401
+ if (reply !== void 0) return {
2402
+ kind: "reply",
2403
+ answer: reply
2404
+ };
2405
+ if (message.text?.body !== void 0) return {
2406
+ kind: "text",
2407
+ answer: message.text.body
2408
+ };
2409
+ if (message.button?.text !== void 0) return {
2410
+ kind: "text",
2411
+ answer: message.button.text
2412
+ };
2413
+ return {
2414
+ kind: "unsupported"
2415
+ };
2416
+ }
2417
+ __name(readFlowInbound, "readFlowInbound");
2418
+
2419
+ // src/flows/matchGlobalKeyword.ts
2420
+ import { normalizeFlowText } from "@adatechnology/meta-whatsapp-contracts";
2421
+ function matchGlobalKeyword(text2, entries) {
2422
+ const normalized = normalizeFlowText(text2);
2423
+ if (normalized.length === 0) return void 0;
2424
+ const padded = ` ${normalized} `;
2425
+ let best;
2426
+ for (const entry of entries) {
2427
+ const isWordMatch = entry.match === "word";
2428
+ for (const keyword of entry.keywords) {
2429
+ const normalizedKeyword = normalizeFlowText(keyword);
2430
+ if (normalizedKeyword.length === 0) continue;
2431
+ const isMatch = isWordMatch ? padded.includes(` ${normalizedKeyword} `) : normalizedKeyword === normalized;
2432
+ if (isMatch && (!best || normalizedKeyword.length > best.length)) {
2433
+ best = {
2434
+ length: normalizedKeyword.length,
2435
+ target: entry.target
2436
+ };
2437
+ }
2438
+ }
2439
+ }
2440
+ return best?.target;
2441
+ }
2442
+ __name(matchGlobalKeyword, "matchGlobalKeyword");
2443
+
2444
+ // src/flows/resolveFlowConfigText.ts
2445
+ async function resolveOne(text2, params) {
2446
+ if (typeof text2 !== "function") return text2;
2447
+ try {
2448
+ return await text2(params.context);
2449
+ } catch (error) {
2450
+ await params.onError?.(error);
2451
+ return void 0;
2452
+ }
2453
+ }
2454
+ __name(resolveOne, "resolveOne");
2455
+ async function resolveFlowConfigText(params) {
2456
+ for (const text2 of params.chain) {
2457
+ const resolved = await resolveOne(text2, params);
2458
+ if (resolved !== void 0) return resolved;
2459
+ }
2460
+ return void 0;
2461
+ }
2462
+ __name(resolveFlowConfigText, "resolveFlowConfigText");
2463
+
2464
+ // src/flows/FlowRunner.ts
2465
+ function contactVariables(profileName) {
2466
+ if (!profileName) return {};
2467
+ return {
2468
+ contactName: profileName,
2469
+ contactFirstName: profileName.trim().split(/\s+/)[0] ?? profileName
2470
+ };
2471
+ }
2472
+ __name(contactVariables, "contactVariables");
2473
+ function resolveFlowTimeZone(config) {
2474
+ const businessHours = config.handoff?.businessHours;
2475
+ const timeZone = config.timeZone ?? (typeof businessHours === "object" ? businessHours.timeZone : void 0);
2476
+ if (!timeZone) throw new ConfigMissingError("features.flowRunner.timeZone");
2477
+ new Intl.DateTimeFormat("en-US", {
2478
+ timeZone
2479
+ });
2480
+ return timeZone;
2481
+ }
2482
+ __name(resolveFlowTimeZone, "resolveFlowTimeZone");
2483
+ var FlowRunner = class {
2484
+ static {
2485
+ __name(this, "FlowRunner");
2486
+ }
2487
+ dependencies;
2488
+ renderer;
2489
+ timeZone;
2490
+ // Variáveis da mensagem em curso, por sessão: é como a action `handoff` (que só recebe a sessão)
2491
+ // enxerga o nome do contato sem que ele precise ir para o contexto gravado.
2492
+ turnVariables = /* @__PURE__ */ new WeakMap();
2493
+ constructor(dependencies) {
2494
+ this.dependencies = dependencies;
2495
+ this.renderer = new FlowQuestionRenderer(dependencies.config);
2496
+ this.timeZone = resolveFlowTimeZone(dependencies.config);
2497
+ }
2498
+ registerDynamicChoiceProvider(key, provider) {
2499
+ this.renderer.registerDynamicChoiceProvider(key, provider);
2500
+ }
2501
+ /**
2502
+ * Variáveis para `{{chave}}`. As do host (`resolveVariables`, `contactName`, `contactFirstName`)
2503
+ * vencem as respostas do cliente: um `contextKey` chamado `contactName` não pode trocar o nome que
2504
+ * o sistema conhece pelo que o cliente digitou.
2505
+ */
2506
+ variablesFor(params) {
2507
+ return {
2508
+ ...params.context,
2509
+ ...this.turnVariables.get(params.session) ?? {}
2510
+ };
2511
+ }
2512
+ /** Atende uma mensagem. Um turno por conversa de cada vez (`lock`); reentrega da mesma mensagem é ignorada. */
2513
+ handle(params) {
2514
+ const key = {
2515
+ companyId: params.companyId,
2516
+ whatsappNumber: params.message.from
2517
+ };
2518
+ return this.dependencies.lock.withLock(key, () => this.handleLocked(params));
2519
+ }
2520
+ /** Abre um fluxo para a conversa sem esperar mensagem — ex.: ao devolver a conversa ao bot. */
2521
+ start(params) {
2522
+ const key = {
2523
+ companyId: params.companyId,
2524
+ whatsappNumber: params.whatsappNumber
2525
+ };
2526
+ return this.dependencies.lock.withLock(key, async () => {
2527
+ const row = await this.dependencies.sessionRepository.getContext(params.companyId, params.whatsappNumber);
2528
+ if (!row) return "no-session";
2529
+ const turn = await this.openTurn({
2530
+ companyId: params.companyId,
2531
+ session: toSessionContract(row),
2532
+ ...params.profileName ? {
2533
+ profileName: params.profileName
2534
+ } : {}
2535
+ });
2536
+ const graph = await this.loadGraph(params.companyId, params.flowKey ?? this.startFlowKey());
2537
+ if (!graph) return "no-flow";
2538
+ turn.isClaimed = true;
2539
+ return this.guard(turn, async () => {
2540
+ await this.runFrom(turn, {
2541
+ graph,
2542
+ nodeId: graph.startNodeId,
2543
+ context: {
2544
+ ...turn.session.context
2545
+ },
2546
+ enterInitialNode: true
2547
+ });
2548
+ return "handled";
2549
+ });
2550
+ });
2551
+ }
2552
+ async handleLocked(params) {
2553
+ const row = await this.dependencies.sessionRepository.getContext(params.companyId, params.message.from);
2554
+ if (!row) return "no-session";
2555
+ if (row.mode === "human") return "human-mode";
2556
+ const session = toSessionContract(row);
2557
+ if (runtimeOf(session.context).lastInboundId === params.message.id) return "duplicate";
2558
+ const turn = await this.openTurn({
2559
+ companyId: params.companyId,
2560
+ session,
2561
+ inboundId: params.message.id,
2562
+ ...params.profileName ? {
2563
+ profileName: params.profileName
2564
+ } : {}
2565
+ });
2566
+ return this.guard(turn, () => this.route(turn, readFlowInbound(params.message)));
2567
+ }
2568
+ async route(turn, inbound) {
2569
+ const globalTarget = inbound.kind === "text" ? this.globalKeywordTarget(inbound.answer) : void 0;
2570
+ if (globalTarget) return this.applyGlobalTarget(turn, globalTarget);
2571
+ const whileAwaitingHuman = this.dependencies.config.whileAwaitingHuman ?? "silent";
2572
+ if (turn.session.humanRequestedAt && !turn.session.currentNodeId && whileAwaitingHuman === "silent") {
2573
+ return "awaiting-human";
2574
+ }
2575
+ const savedFlowKey = turn.session.flowKey;
2576
+ const savedGraph = await this.loadGraph(turn.companyId, savedFlowKey ?? this.startFlowKey());
2577
+ const isStale = !savedGraph && savedFlowKey !== null && savedFlowKey !== this.startFlowKey();
2578
+ const graph = savedGraph ?? (isStale ? await this.loadGraph(turn.companyId, this.startFlowKey()) : void 0);
2579
+ if (!graph) return "no-flow";
2580
+ await this.claim(turn);
2581
+ if (isStale) await this.report(turn, savedFlowKey, turn.session.currentNodeId, "cross-flow", new FlowRunnerError2("flow-not-found", savedFlowKey));
2582
+ const node = !isStale && turn.session.currentNodeId ? graph.nodes[turn.session.currentNodeId] : void 0;
2583
+ const context = {
2584
+ ...turn.session.context
2585
+ };
2586
+ if (node) {
2587
+ await this.answerNode({
2588
+ turn,
2589
+ graph,
2590
+ node,
2591
+ context,
2592
+ inbound
2593
+ });
2594
+ return "handled";
2595
+ }
2596
+ const start = graph.nodes[graph.startNodeId];
2597
+ const target = start && inbound.kind !== "unsupported" ? this.keywordJumpAtStart(start, inbound) : void 0;
2598
+ if (target) await this.jumpTo(turn, graph, target, context);
2599
+ else await this.runFrom(turn, {
2600
+ graph,
2601
+ nodeId: graph.startNodeId,
2602
+ context,
2603
+ enterInitialNode: true
2604
+ });
2605
+ return "handled";
2606
+ }
2607
+ async guard(turn, work) {
2608
+ try {
2609
+ return await work();
2610
+ } catch (error) {
2611
+ if (!turn.isClaimed) throw error;
2612
+ await this.report(turn, turn.session.flowKey, turn.session.currentNodeId, "turn", error);
2613
+ return "handled";
2614
+ }
2615
+ }
2616
+ /** Primeira escrita do turno: grava o id da mensagem antes de qualquer efeito externo. */
2617
+ async claim(turn) {
2618
+ if (turn.isClaimed) return;
2619
+ await this.save(turn, {
2620
+ flowKey: turn.session.flowKey,
2621
+ nodeId: turn.session.currentNodeId,
2622
+ context: {
2623
+ ...turn.session.context
2624
+ }
2625
+ });
2626
+ turn.isClaimed = true;
2627
+ }
2628
+ async openTurn(params) {
2629
+ const { session, profileName } = params;
2630
+ const resolver = this.dependencies.config.resolveVariables;
2631
+ const hostVariables = resolver ? await resolver({
2632
+ session,
2633
+ ...profileName ? {
2634
+ profileName
2635
+ } : {}
2636
+ }) : {};
2637
+ const baseVariables = {
2638
+ ...contactVariables(profileName),
2639
+ ...hostVariables
2640
+ };
2641
+ this.turnVariables.set(session, baseVariables);
2642
+ return {
2643
+ companyId: params.companyId,
2644
+ session,
2645
+ baseVariables,
2646
+ ...params.inboundId ? {
2647
+ inboundId: params.inboundId
2648
+ } : {},
2649
+ isClaimed: false
2650
+ };
2651
+ }
2652
+ startFlowKey() {
2653
+ return this.dependencies.config.startFlowKey ?? DEFAULT_START_FLOW_KEY;
2654
+ }
2655
+ clock() {
2656
+ const { config } = this.dependencies;
2657
+ return {
2658
+ now: config.now?.() ?? /* @__PURE__ */ new Date(),
2659
+ locale: config.dateLocale ?? FLOW_DATE_LOCALE_PT_BR,
2660
+ timeZone: this.timeZone
2661
+ };
2662
+ }
2663
+ loadGraph(companyId, flowKey) {
2664
+ return this.dependencies.flowGraphRepository.get(companyId, flowKey);
2665
+ }
2666
+ globalKeywordTarget(answer) {
2667
+ return matchGlobalKeyword(answer, this.dependencies.config.globalKeywords ?? []);
2668
+ }
2669
+ keywordJumpAtStart(start, inbound) {
2670
+ if (inbound.kind === "unsupported") return void 0;
2671
+ const decision = resolveFlowAnswer({
2672
+ node: start,
2673
+ answer: inbound.answer,
2674
+ isInteractiveReply: inbound.kind === "reply",
2675
+ context: {},
2676
+ clock: this.clock()
2677
+ });
2678
+ return decision.kind === "jump" ? decision.target : void 0;
2679
+ }
2680
+ /**
2681
+ * Palavra global vale mesmo com a conversa aguardando atendimento. Reiniciar NÃO tira o pedido da
2682
+ * fila (`humanRequestedAt` continua): a equipe ainda responde, e o cliente pode usar o bot enquanto
2683
+ * espera; quando o fluxo terminar, o runner volta ao silêncio.
2684
+ */
2685
+ async applyGlobalTarget(turn, target) {
2686
+ const context = withRuntime({
2687
+ ...turn.session.context
2688
+ }, {});
2689
+ if (target === "handoff") {
2690
+ await this.claim(turn);
2691
+ await this.handOff(turn, context);
2692
+ return "handled";
2693
+ }
2694
+ const flowKey = target === "restart" ? this.startFlowKey() : crossFlowKey2(target);
2695
+ const graph = await this.loadGraph(turn.companyId, flowKey);
2696
+ if (!graph) return "no-flow";
2697
+ await this.claim(turn);
2698
+ await this.runFrom(turn, {
2699
+ graph,
2700
+ nodeId: graph.startNodeId,
2701
+ context,
2702
+ enterInitialNode: true
2703
+ });
2704
+ return "handled";
2705
+ }
2706
+ async answerNode(params) {
2707
+ const { turn, graph, node, context, inbound } = params;
2708
+ const runtime = runtimeOf(context);
2709
+ const dynamic = runtime.dynamic?.nodeId === node.id ? runtime.dynamic : void 0;
2710
+ const page = dynamic?.page ?? 0;
2711
+ if (inbound.kind === "unsupported") {
2712
+ const text2 = await this.configText(turn, node, {
2713
+ chain: [
2714
+ this.dependencies.config.nonTextAnswerMessage
2715
+ ],
2716
+ kind: "non-text-answer"
2717
+ });
2718
+ await this.say(turn, text2 ?? DEFAULT_FLOW_TEXT.NON_TEXT_ANSWER, context);
2719
+ return this.awaitAnswer(turn, graph, node, context, page);
2720
+ }
2721
+ const decision = resolveFlowAnswer({
2722
+ node,
2723
+ answer: inbound.answer,
2724
+ isInteractiveReply: inbound.kind === "reply",
2725
+ context,
2726
+ clock: this.clock(),
2727
+ ...dynamic ? {
2728
+ dynamicOptions: dynamic.options
2729
+ } : {},
2730
+ ...isChoiceNode(node) ? {
2731
+ options: this.renderedOptions(turn, node, context)
2732
+ } : {}
2733
+ });
2734
+ if (decision.kind === "jump") return this.jumpTo(turn, graph, decision.target, withRuntime(context, {}));
2735
+ if (decision.kind === "see-more") return this.awaitAnswer(turn, graph, node, context, page + 1);
2736
+ if (decision.kind === "invalid" && this.followsDefaultWhenUnmatched(node)) {
2737
+ return this.runFrom(turn, {
2738
+ graph,
2739
+ nodeId: node.id,
2740
+ context: withRuntime(context, {}),
2741
+ userAnswer: inbound.answer,
2742
+ enterInitialNode: false
2743
+ });
2744
+ }
2745
+ if (decision.kind === "invalid") {
2746
+ return this.handleInvalid(turn, graph, node, context, {
2747
+ rejection: decision.rejection
2748
+ });
2749
+ }
2750
+ const hostRejection = await this.validateWithHost(turn, node, context, {
2751
+ answer: inbound.answer,
2752
+ value: decision.value
2753
+ });
2754
+ if (hostRejection) return this.handleInvalid(turn, graph, node, context, hostRejection);
2755
+ await this.runFrom(turn, {
2756
+ graph,
2757
+ nodeId: node.id,
2758
+ context: withRuntime(context, {}),
2759
+ userAnswer: decision.userAnswer,
2760
+ ...decision.value !== void 0 ? {
2761
+ answerValue: decision.value
2762
+ } : {},
2763
+ enterInitialNode: false
2764
+ });
2765
+ }
2766
+ /** Títulos como o cliente os viu (`{{chave}}` resolvido): é contra eles que o texto digitado casa. */
2767
+ renderedOptions(turn, node, context) {
2768
+ const variables = {
2769
+ ...context,
2770
+ ...turn.baseVariables
2771
+ };
2772
+ return (node.options ?? []).map(([id, title]) => [
2773
+ id,
2774
+ this.renderer.interpolate(title, variables)
2775
+ ]);
2776
+ }
2777
+ /**
2778
+ * Validador do host, só para pergunta (escolha já casou com opção) e nunca para resposta pulada.
2779
+ * Falha do validador não pode prender o cliente na pergunta: reporta e aceita.
2780
+ */
2781
+ async validateWithHost(turn, node, context, answer) {
2782
+ const validator = this.dependencies.config.validateAnswer;
2783
+ if (!validator || isChoiceNode(node) || node.type === "dynamic_choice" || answer.value === null) return void 0;
2784
+ try {
2785
+ const result = await validator({
2786
+ companyId: turn.companyId,
2787
+ session: turn.session,
2788
+ node,
2789
+ answer: answer.answer.trim(),
2790
+ value: answer.value ?? answer.answer,
2791
+ context
2792
+ });
2793
+ if (!result || result.isValid) return void 0;
2794
+ return {
2795
+ rejection: "rejected-by-host",
2796
+ ...result.message ? {
2797
+ message: result.message
2798
+ } : {}
2799
+ };
2800
+ } catch (error) {
2801
+ await this.report(turn, turn.session.flowKey, node.id, "validate-answer", error);
2802
+ return void 0;
2803
+ }
2804
+ }
2805
+ configText(turn, node, params) {
2806
+ return resolveFlowConfigText({
2807
+ chain: params.chain,
2808
+ context: {
2809
+ companyId: turn.companyId,
2810
+ whatsappNumber: turn.session.whatsappNumber,
2811
+ kind: params.kind,
2812
+ flowKey: turn.session.flowKey,
2813
+ ...node ? {
2814
+ nodeId: node.id
2815
+ } : {},
2816
+ ...params.rejection ? {
2817
+ rejection: params.rejection
2818
+ } : {}
2819
+ },
2820
+ onError: /* @__PURE__ */ __name((error) => this.report(turn, turn.session.flowKey, node?.id ?? null, "text", error), "onError")
2821
+ });
2822
+ }
2823
+ followsDefaultWhenUnmatched(node) {
2824
+ if (!isChoiceNode(node)) return false;
2825
+ return (node.unmatchedChoice ?? this.dependencies.config.unmatchedChoice ?? "reask") === "default";
2826
+ }
2827
+ async handleInvalid(turn, graph, node, context, invalid) {
2828
+ const runtime = runtimeOf(context);
2829
+ const attempts = (runtime.invalidAnswers ?? 0) + 1;
2830
+ const limit = node.maxInvalidAnswers ?? this.dependencies.config.maxInvalidAnswers ?? DEFAULT_MAX_INVALID_ANSWERS;
2831
+ if (attempts >= limit) return this.handOff(turn, withRuntime(context, {}));
2832
+ const updated = withRuntime(context, {
2833
+ ...runtime,
2834
+ invalidAnswers: attempts
2835
+ });
2836
+ await this.say(turn, await this.fallbackText(turn, node, invalid), updated);
2837
+ await this.awaitAnswer(turn, graph, node, updated, runtime.dynamic?.nodeId === node.id ? runtime.dynamic.page : 0);
2838
+ }
2839
+ /** Precedência: texto do validador do host, `fallbackMessage` do nó, texto do motivo, padrão do host, do pacote. */
2840
+ async fallbackText(turn, node, invalid) {
2841
+ const { config } = this.dependencies;
2842
+ const fixed = invalid.message ?? node.fallbackMessage;
2843
+ if (fixed !== void 0) return fixed;
2844
+ const { rejection } = invalid;
2845
+ const byRejection = rejection ? await this.configText(turn, node, {
2846
+ chain: [
2847
+ config.rejectionMessages?.[rejection]
2848
+ ],
2849
+ kind: "rejection",
2850
+ rejection
2851
+ }) : void 0;
2852
+ if (byRejection !== void 0) return byRejection;
2853
+ const fallback = await this.configText(turn, node, {
2854
+ chain: [
2855
+ config.defaultFallbackMessage
2856
+ ],
2857
+ kind: "fallback"
2858
+ });
2859
+ return fallback ?? DEFAULT_FLOW_TEXT.FALLBACK;
2860
+ }
2861
+ async handOff(turn, context) {
2862
+ const isWithinHours = await this.dependencies.handoff.request({
2863
+ companyId: turn.companyId,
2864
+ whatsappNumber: turn.session.whatsappNumber,
2865
+ variables: {
2866
+ ...context,
2867
+ ...turn.baseVariables
2868
+ }
2869
+ });
2870
+ await this.save(turn, {
2871
+ flowKey: null,
2872
+ nodeId: null,
2873
+ context: {
2874
+ ...context,
2875
+ handoffWithinBusinessHours: isWithinHours
2876
+ }
2877
+ });
2878
+ }
2879
+ async jumpTo(turn, graph, target, context) {
2880
+ if (isCrossFlowTarget2(target)) {
2881
+ const targetGraph = await this.loadGraph(turn.companyId, crossFlowKey2(target));
2882
+ if (!targetGraph) return this.reportMissingFlow(turn, graph.key, target, context);
2883
+ return this.runFrom(turn, {
2884
+ graph: targetGraph,
2885
+ nodeId: targetGraph.startNodeId,
2886
+ context,
2887
+ enterInitialNode: true
2888
+ });
2889
+ }
2890
+ return this.runFrom(turn, {
2891
+ graph,
2892
+ nodeId: target,
2893
+ context,
2894
+ enterInitialNode: true
2895
+ });
2896
+ }
2897
+ async runFrom(turn, initial) {
2898
+ const maxJumps = this.dependencies.config.maxCrossFlowJumps ?? DEFAULT_MAX_CROSS_FLOW_JUMPS;
2899
+ let params = initial;
2900
+ for (let jump = 0; jump <= maxJumps; jump++) {
2901
+ const result = await this.dependencies.interpreter.run({
2902
+ graph: params.graph,
2903
+ currentNodeId: params.nodeId,
2904
+ ...params.userAnswer !== void 0 ? {
2905
+ userAnswer: params.userAnswer
2906
+ } : {},
2907
+ ...params.answerValue !== void 0 ? {
2908
+ answerValue: params.answerValue
2909
+ } : {},
2910
+ context: params.context,
2911
+ session: turn.session,
2912
+ channel: this.dependencies.channel
2913
+ }, {
2914
+ enterInitialNode: params.enterInitialNode,
2915
+ onNodeEntered: /* @__PURE__ */ __name(async (node, context) => {
2916
+ if (node.directMessage) await this.say(turn, node.directMessage, context);
2917
+ }, "onNodeEntered")
2918
+ });
2919
+ if (result.kind === "awaiting-answer") {
2920
+ const node = params.graph.nodes[result.nodeId];
2921
+ if (node) return this.awaitAnswer(turn, params.graph, node, result.context, 0);
2922
+ return this.save(turn, {
2923
+ flowKey: null,
2924
+ nodeId: null,
2925
+ context: result.context
2926
+ });
2927
+ }
2928
+ if (result.kind === "terminal") return this.save(turn, {
2929
+ flowKey: null,
2930
+ nodeId: null,
2931
+ context: result.context
2932
+ });
2933
+ if (result.kind === "max-steps-exceeded") {
2934
+ await this.save(turn, {
2935
+ flowKey: null,
2936
+ nodeId: null,
2937
+ context: result.context
2938
+ });
2939
+ return this.report(turn, params.graph.key, null, "max-steps", new FlowRunnerError2("cycle", result.visited.join(" -> ")));
2940
+ }
2941
+ const target = await this.loadGraph(turn.companyId, result.flowKey);
2942
+ if (!target) return this.reportMissingFlow(turn, params.graph.key, result.flowKey, result.context);
2943
+ params = {
2944
+ graph: target,
2945
+ nodeId: target.startNodeId,
2946
+ context: result.context,
2947
+ enterInitialNode: true
2948
+ };
2949
+ }
2950
+ await this.save(turn, {
2951
+ flowKey: null,
2952
+ nodeId: null,
2953
+ context: params.context
2954
+ });
2955
+ return this.report(turn, params.graph.key, null, "cross-flow", new FlowRunnerError2("too-many-jumps", params.graph.key));
2956
+ }
2957
+ /** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
2958
+ async awaitAnswer(turn, graph, node, context, page) {
2959
+ try {
2960
+ const { message, context: renderedContext } = await this.renderer.prepare({
2961
+ session: turn.session,
2962
+ variables: turn.baseVariables,
2963
+ node,
2964
+ context,
2965
+ page
2966
+ });
2967
+ await this.save(turn, {
2968
+ flowKey: graph.key,
2969
+ nodeId: node.id,
2970
+ context: renderedContext
2971
+ });
2972
+ if (message) await this.send(turn, message);
2973
+ } catch (error) {
2974
+ await this.report(turn, graph.key, node.id, "render", error);
2975
+ }
2976
+ }
2977
+ async say(turn, template, context) {
2978
+ const body = this.renderer.interpolate(template, {
2979
+ ...context,
2980
+ ...turn.baseVariables
2981
+ });
2982
+ if (body.trim().length > 0) await this.send(turn, {
2983
+ kind: "text",
2984
+ body
2985
+ });
2986
+ }
2987
+ async send(turn, message) {
2988
+ const common = {
2989
+ companyId: turn.companyId,
2990
+ whatsappNumber: turn.session.whatsappNumber,
2991
+ sender: "bot",
2992
+ startState: this.dependencies.startState
2993
+ };
2994
+ if (message.kind === "text") await this.dependencies.sendMessage.sendText({
2995
+ ...common,
2996
+ body: message.body
2997
+ });
2998
+ else await this.dependencies.sendMessage.sendInteractive({
2999
+ ...common,
3000
+ interactive: message.interactive
3001
+ });
3002
+ }
3003
+ save(turn, progress) {
3004
+ const runtime = runtimeOf(progress.context);
3005
+ const context = turn.inboundId ? withRuntime(progress.context, {
3006
+ ...runtime,
3007
+ lastInboundId: turn.inboundId
3008
+ }) : progress.context;
3009
+ return this.dependencies.sessionRepository.saveFlowProgress(turn.companyId, turn.session.whatsappNumber, {
3010
+ flowKey: progress.flowKey,
3011
+ currentNodeId: progress.nodeId,
3012
+ context
3013
+ });
3014
+ }
3015
+ async reportMissingFlow(turn, fromFlowKey, target, context) {
3016
+ await this.save(turn, {
3017
+ flowKey: null,
3018
+ nodeId: null,
3019
+ context
3020
+ });
3021
+ await this.report(turn, fromFlowKey, null, "cross-flow", new FlowRunnerError2("flow-not-found", target));
3022
+ }
3023
+ /**
3024
+ * Nunca relança: só é chamado depois de o turno ter sido gravado, e relançar faria a fila repetir
3025
+ * uma mensagem já marcada como tratada. Sem gancho, o erro é descartado (a conversa fica no último
3026
+ * ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
3027
+ */
3028
+ async report(turn, flowKey, nodeId, stage, error) {
3029
+ const details = {
3030
+ companyId: turn.companyId,
3031
+ whatsappNumber: turn.session.whatsappNumber,
3032
+ flowKey,
3033
+ nodeId,
3034
+ stage
3035
+ };
3036
+ try {
3037
+ await this.dependencies.hooks?.onFlowRunnerError?.(error, details);
3038
+ } catch {
3039
+ }
3040
+ }
3041
+ };
3042
+
3043
+ // src/flows/FlowHandoff.ts
3044
+ import { interpolateFlowText as interpolateFlowText2, isWithinBusinessHours } from "@adatechnology/meta-whatsapp-contracts";
3045
+ function readParam(node, key) {
3046
+ const value = node?.actionParams?.[key];
3047
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
3048
+ }
3049
+ __name(readParam, "readParam");
3050
+ var FlowHandoff = class {
3051
+ static {
3052
+ __name(this, "FlowHandoff");
3053
+ }
3054
+ dependencies;
3055
+ constructor(dependencies) {
3056
+ this.dependencies = dependencies;
3057
+ }
3058
+ /** Devolve se caiu dentro do horário — vai para o contexto como `handoffWithinBusinessHours`. */
3059
+ async request(params) {
3060
+ const { requestHuman, sendMessage, startState, interpolation } = this.dependencies;
3061
+ try {
3062
+ await requestHuman.execute({
3063
+ companyId: params.companyId,
3064
+ whatsappNumber: params.whatsappNumber
3065
+ });
3066
+ } catch (error) {
3067
+ await this.reportFailure(error, params, "handoff");
3068
+ }
3069
+ const isWithinHours = await this.isWithinHours(params.companyId);
3070
+ const template = await this.messageFor(isWithinHours, params);
3071
+ await sendMessage.sendText({
3072
+ companyId: params.companyId,
3073
+ whatsappNumber: params.whatsappNumber,
3074
+ body: interpolateFlowText2(template, params.variables, interpolation),
3075
+ sender: "bot",
3076
+ startState
3077
+ });
3078
+ return isWithinHours;
3079
+ }
3080
+ /**
3081
+ * Handler do `actionKind: 'handoff'`. `actionParams.message` e `actionParams.outOfHoursMessage`
3082
+ * sobrescrevem os textos do runner para aquele nó.
3083
+ */
3084
+ createActionHandler(resolveVariables) {
3085
+ return async ({ node, session, context }) => {
3086
+ const isWithinHours = await this.request({
3087
+ companyId: session.companyId,
3088
+ whatsappNumber: session.whatsappNumber,
3089
+ variables: resolveVariables({
3090
+ session,
3091
+ context
3092
+ }),
3093
+ node
3094
+ });
3095
+ return {
3096
+ context: {
3097
+ handoffWithinBusinessHours: isWithinHours
3098
+ }
3099
+ };
3100
+ };
3101
+ }
3102
+ async reportFailure(error, params, stage) {
3103
+ try {
3104
+ await this.dependencies.hooks?.onFlowRunnerError?.(error, {
3105
+ companyId: params.companyId,
3106
+ whatsappNumber: params.whatsappNumber,
3107
+ flowKey: null,
3108
+ nodeId: params.node?.id ?? null,
3109
+ stage
3110
+ });
3111
+ } catch {
3112
+ }
3113
+ }
3114
+ async isWithinHours(companyId) {
3115
+ const source = this.dependencies.config.businessHours;
3116
+ const hours = typeof source === "function" ? await source(companyId) : source;
3117
+ return hours ? isWithinBusinessHours(hours, this.dependencies.now()) : true;
3118
+ }
3119
+ async messageFor(isWithinHours, params) {
3120
+ const { config } = this.dependencies;
3121
+ const { node } = params;
3122
+ const chain = isWithinHours ? [
3123
+ readParam(node, "message"),
3124
+ config.message,
3125
+ DEFAULT_FLOW_TEXT.HANDOFF
3126
+ ] : [
3127
+ readParam(node, "outOfHoursMessage"),
3128
+ config.outOfHoursMessage,
3129
+ readParam(node, "message"),
3130
+ config.message,
3131
+ DEFAULT_FLOW_TEXT.HANDOFF_OUT_OF_HOURS
3132
+ ];
3133
+ const text2 = await resolveFlowConfigText({
3134
+ chain,
3135
+ context: {
3136
+ companyId: params.companyId,
3137
+ whatsappNumber: params.whatsappNumber,
3138
+ kind: isWithinHours ? "handoff" : "handoff-out-of-hours",
3139
+ ...node ? {
3140
+ nodeId: node.id
3141
+ } : {}
3142
+ },
3143
+ onError: /* @__PURE__ */ __name((error) => this.reportFailure(error, params, "text"), "onError")
3144
+ });
3145
+ return text2 ?? DEFAULT_FLOW_TEXT.HANDOFF;
3146
+ }
3147
+ };
3148
+
3149
+ // src/flows/flowTurnLock.ts
3150
+ import { sql as sql5 } from "drizzle-orm";
3151
+ function lockName(key) {
3152
+ return `meta_whatsapp_flow:${key.companyId}:${key.whatsappNumber}`;
3153
+ }
3154
+ __name(lockName, "lockName");
3155
+ var PostgresAdvisoryFlowTurnLock = class {
3156
+ static {
3157
+ __name(this, "PostgresAdvisoryFlowTurnLock");
3158
+ }
3159
+ db;
3160
+ constructor(db) {
3161
+ this.db = db;
3162
+ }
3163
+ withLock(key, work) {
3164
+ return this.db.transaction(async (transaction) => {
3165
+ await transaction.execute(sql5`select pg_advisory_xact_lock(hashtext(${lockName(key)}))`);
3166
+ return work();
3167
+ });
3168
+ }
3169
+ };
3170
+ var InProcessFlowTurnLock = class {
3171
+ static {
3172
+ __name(this, "InProcessFlowTurnLock");
3173
+ }
3174
+ tails = /* @__PURE__ */ new Map();
3175
+ async withLock(key, work) {
3176
+ const name = lockName(key);
3177
+ const previous = this.tails.get(name) ?? Promise.resolve();
3178
+ const current = previous.catch(() => void 0).then(work);
3179
+ this.tails.set(name, current);
3180
+ try {
3181
+ return await current;
3182
+ } finally {
3183
+ if (this.tails.get(name) === current) this.tails.delete(name);
3184
+ }
3185
+ }
3186
+ };
3187
+
2047
3188
  // src/flows/createSendMediaAction.ts
2048
3189
  function mediaTypeFor2(mimeType) {
2049
3190
  if (mimeType.startsWith("image/")) return "image";
@@ -2209,7 +3350,7 @@ async function listAvailableProducts(params) {
2209
3350
  __name(listAvailableProducts, "listAvailableProducts");
2210
3351
 
2211
3352
  // src/repositories/FlowMediaRepository.ts
2212
- import { and as and5, asc as asc2, eq as eq6, sql as sql5 } from "drizzle-orm";
3353
+ import { and as and5, asc as asc2, eq as eq6, sql as sql6 } from "drizzle-orm";
2213
3354
  var FlowMediaRepository = class {
2214
3355
  static {
2215
3356
  __name(this, "FlowMediaRepository");
@@ -2261,7 +3402,7 @@ var FlowMediaRepository = class {
2261
3402
  caption: params.caption ?? null,
2262
3403
  sortOrder: params.sortOrder ?? 0,
2263
3404
  active: true,
2264
- updatedAt: sql5`now()`
3405
+ updatedAt: sql6`now()`
2265
3406
  }
2266
3407
  }).returning();
2267
3408
  return row;
@@ -2277,7 +3418,7 @@ var FlowMediaRepository = class {
2277
3418
  ...params.active !== void 0 ? {
2278
3419
  active: params.active
2279
3420
  } : {},
2280
- updatedAt: sql5`now()`
3421
+ updatedAt: sql6`now()`
2281
3422
  }).where(and5(eq6(flowMedia.companyId, params.companyId), eq6(flowMedia.id, params.id))).returning();
2282
3423
  return row;
2283
3424
  }
@@ -2291,13 +3432,13 @@ var FlowMediaRepository = class {
2291
3432
  }
2292
3433
  // Chamado ao salvar o grafo: nós apagados no editor deixam linhas que nada mais alcança.
2293
3434
  async detachRemovedNodes(params) {
2294
- const condition = params.existingNodeIds.length === 0 ? void 0 : sql5`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
3435
+ const condition = params.existingNodeIds.length === 0 ? void 0 : sql6`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
2295
3436
  await this.db.delete(flowMedia).where(and5(eq6(flowMedia.companyId, params.companyId), eq6(flowMedia.flowKey, params.flowKey), condition));
2296
3437
  }
2297
3438
  };
2298
3439
 
2299
3440
  // src/repositories/FlowMediaIdRepository.ts
2300
- import { eq as eq7, sql as sql6 } from "drizzle-orm";
3441
+ import { eq as eq7, sql as sql7 } from "drizzle-orm";
2301
3442
  var FlowMediaIdRepository = class {
2302
3443
  static {
2303
3444
  __name(this, "FlowMediaIdRepository");
@@ -2321,20 +3462,20 @@ var FlowMediaIdRepository = class {
2321
3462
  */
2322
3463
  async set(params) {
2323
3464
  await this.db.update(flowMedia).set({
2324
- metaMediaIds: sql6`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
3465
+ metaMediaIds: sql7`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
2325
3466
  }).where(eq7(flowMedia.id, params.flowMediaId));
2326
3467
  }
2327
3468
  /** Remove só a chave deste número — o id do outro número continua válido. */
2328
3469
  async clear(params) {
2329
3470
  await this.db.update(flowMedia).set({
2330
- metaMediaIds: sql6`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
3471
+ metaMediaIds: sql7`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
2331
3472
  }).where(eq7(flowMedia.id, params.flowMediaId));
2332
3473
  }
2333
3474
  };
2334
3475
 
2335
3476
  // src/channel/WhatsAppChannelAdapter.ts
2336
3477
  import { WhatsAppWindowExpiredError as ProviderWindowExpiredError } from "@adatechnology/meta-graph-core";
2337
- import { WindowExpiredError as WindowExpiredError2 } from "@adatechnology/meta-whatsapp-contracts";
3478
+ import { WindowExpiredError as WindowExpiredError2, isPreviewContact } from "@adatechnology/meta-whatsapp-contracts";
2338
3479
 
2339
3480
  // src/channel/previewMedia.ts
2340
3481
  import { PREVIEW_MEDIA_ID_PREFIX, toPreviewMediaId, resolvePreviewUploadId } from "@adatechnology/meta-whatsapp-contracts";
@@ -2346,9 +3487,16 @@ var WhatsAppChannelAdapter = class {
2346
3487
  }
2347
3488
  messages;
2348
3489
  previewMedia;
2349
- constructor(messages2, previewMedia) {
3490
+ previewContacts;
3491
+ constructor(messages2, previewMedia, previewContacts) {
2350
3492
  this.messages = messages2;
2351
3493
  this.previewMedia = previewMedia;
3494
+ this.previewContacts = previewContacts;
3495
+ }
3496
+ /** `preview.<uuid>` quando o destino é contato do simulador e o recurso está ligado. */
3497
+ previewMessageId(to) {
3498
+ if (!this.previewContacts?.isEnabled || !isPreviewContact(to)) return void 0;
3499
+ return `preview.${this.previewContacts.generateId?.() ?? globalThis.crypto.randomUUID()}`;
2352
3500
  }
2353
3501
  async translateErrors(operation) {
2354
3502
  try {
@@ -2359,12 +3507,20 @@ var WhatsAppChannelAdapter = class {
2359
3507
  }
2360
3508
  }
2361
3509
  async sendText(to, body) {
3510
+ const previewId = this.previewMessageId(to);
3511
+ if (previewId) return {
3512
+ externalMessageId: previewId
3513
+ };
2362
3514
  const result = await this.translateErrors(() => this.messages.sendText(to, body));
2363
3515
  return {
2364
3516
  externalMessageId: result.waMessageId
2365
3517
  };
2366
3518
  }
2367
3519
  async sendMedia(params) {
3520
+ const previewId = this.previewMessageId(params.to);
3521
+ if (previewId) return {
3522
+ externalMessageId: previewId
3523
+ };
2368
3524
  const result = await this.translateErrors(() => this.messages.sendMedia(params));
2369
3525
  return {
2370
3526
  externalMessageId: result.waMessageId,
@@ -2372,12 +3528,20 @@ var WhatsAppChannelAdapter = class {
2372
3528
  };
2373
3529
  }
2374
3530
  async sendTemplate(params) {
3531
+ const previewId = this.previewMessageId(params.to);
3532
+ if (previewId) return {
3533
+ externalMessageId: previewId
3534
+ };
2375
3535
  const result = await this.translateErrors(() => this.messages.sendTemplate(params));
2376
3536
  return {
2377
3537
  externalMessageId: result.waMessageId
2378
3538
  };
2379
3539
  }
2380
3540
  async sendInteractiveList(params) {
3541
+ const previewId = this.previewMessageId(params.to);
3542
+ if (previewId) return {
3543
+ externalMessageId: previewId
3544
+ };
2381
3545
  const sections = (params.sections ?? [
2382
3546
  {
2383
3547
  rows: params.rows ?? []
@@ -2403,6 +3567,10 @@ var WhatsAppChannelAdapter = class {
2403
3567
  };
2404
3568
  }
2405
3569
  async sendInteractiveButtons(params) {
3570
+ const previewId = this.previewMessageId(params.to);
3571
+ if (previewId) return {
3572
+ externalMessageId: previewId
3573
+ };
2406
3574
  const result = await this.translateErrors(() => this.messages.sendInteractiveButtons({
2407
3575
  to: params.to,
2408
3576
  bodyText: params.body,
@@ -2413,6 +3581,10 @@ var WhatsAppChannelAdapter = class {
2413
3581
  };
2414
3582
  }
2415
3583
  async sendProductList(params) {
3584
+ const previewId = this.previewMessageId(params.to);
3585
+ if (previewId) return {
3586
+ externalMessageId: previewId
3587
+ };
2416
3588
  const result = await this.translateErrors(() => this.messages.sendProductListMessage({
2417
3589
  to: params.to,
2418
3590
  headerText: params.headerText,
@@ -2860,6 +4032,9 @@ var ReceiveWebhookUseCase = class {
2860
4032
  } : {},
2861
4033
  ...params.realtime ? {
2862
4034
  realtime: params.realtime
4035
+ } : {},
4036
+ ...params.flowRunner ? {
4037
+ flowRunner: params.flowRunner
2863
4038
  } : {}
2864
4039
  });
2865
4040
  }
@@ -3025,6 +4200,7 @@ var ReceiveWebhookUseCase = class {
3025
4200
  });
3026
4201
  if (!updated) return;
3027
4202
  this.params.realtime?.emit(`conv:${updated.whatsappNumber}`, "message-status", {
4203
+ companyId,
3028
4204
  waMessageId: status.id,
3029
4205
  status: status.status
3030
4206
  });
@@ -3116,7 +4292,9 @@ function createMetaWhatsAppModule(params) {
3116
4292
  isEnabled: true,
3117
4293
  objectStorage: providers.objectStorage
3118
4294
  } : void 0;
3119
- const channel = new WhatsAppChannelAdapter(messageProvider, previewMediaSupport);
4295
+ const channel = new WhatsAppChannelAdapter(messageProvider, previewMediaSupport, params.features?.previewContacts ? {
4296
+ isEnabled: true
4297
+ } : void 0);
3120
4298
  const sessionRepository = new SessionRepository(db);
3121
4299
  const messageRepository = new MessageRepository(db);
3122
4300
  const settingsRepository = new SettingsRepository(db);
@@ -3127,6 +4305,40 @@ function createMetaWhatsAppModule(params) {
3127
4305
  const flowMediaRepository = new FlowMediaRepository(db);
3128
4306
  const logMessage = new LogMessageUseCase(sessionRepository, messageRepository, providers.realtime, providers.moderator);
3129
4307
  const sendMessage = new SendMessageUseCase(channel, sessionRepository, logMessage, providers.objectStorage, documentRepository);
4308
+ const requestHuman = new RequestHumanConversationUseCase(sessionRepository, providers.realtime, hooks);
4309
+ const flowInterpreter = flowEngineEnabled ? new FlowInterpreter() : void 0;
4310
+ const flowRunnerFeature = params.features?.flowRunner ?? false;
4311
+ const flowRunnerConfig = flowInterpreter && flowRunnerFeature ? flowRunnerFeature === true ? {} : flowRunnerFeature : void 0;
4312
+ const flowHandoff = flowRunnerConfig ? new FlowHandoff({
4313
+ requestHuman,
4314
+ sendMessage,
4315
+ startState,
4316
+ config: flowRunnerConfig.handoff ?? {},
4317
+ now: flowRunnerConfig.now ?? (() => /* @__PURE__ */ new Date()),
4318
+ interpolation: flowRunnerConfig.formatValue ? {
4319
+ formatValue: flowRunnerConfig.formatValue
4320
+ } : {},
4321
+ ...hooks ? {
4322
+ hooks
4323
+ } : {}
4324
+ }) : void 0;
4325
+ const flowRunner = flowInterpreter && flowRunnerConfig && flowHandoff ? new FlowRunner({
4326
+ interpreter: flowInterpreter,
4327
+ flowGraphRepository,
4328
+ sessionRepository,
4329
+ sendMessage,
4330
+ channel,
4331
+ handoff: flowHandoff,
4332
+ lock: providers.flowTurnLock ?? new PostgresAdvisoryFlowTurnLock(db),
4333
+ startState,
4334
+ config: flowRunnerConfig,
4335
+ ...hooks ? {
4336
+ hooks
4337
+ } : {}
4338
+ }) : void 0;
4339
+ if (flowInterpreter && flowRunner && flowHandoff) {
4340
+ flowInterpreter.registerFlowAction(FLOW_ACTION_KIND.HANDOFF, flowHandoff.createActionHandler((turn) => flowRunner.variablesFor(turn)));
4341
+ }
3130
4342
  const receiveWebhook = new ReceiveWebhookUseCase({
3131
4343
  appSecret: config.appSecret,
3132
4344
  phoneNumberId: config.phoneNumberId,
@@ -3140,9 +4352,11 @@ function createMetaWhatsAppModule(params) {
3140
4352
  ...providers.inboundQueue ? {
3141
4353
  inboundQueue: providers.inboundQueue
3142
4354
  } : {},
3143
- redactInboundLocation: params.features?.redactInboundLocation ?? false
4355
+ redactInboundLocation: params.features?.redactInboundLocation ?? false,
4356
+ ...flowRunner ? {
4357
+ flowRunner
4358
+ } : {}
3144
4359
  });
3145
- const flowInterpreter = flowEngineEnabled ? new FlowInterpreter() : void 0;
3146
4360
  if (flowInterpreter && providers.objectStorage?.getObject) {
3147
4361
  flowInterpreter.registerFlowAction(FLOW_ACTION_KIND.SEND_MEDIA, createSendMediaAction({
3148
4362
  flowMediaRepository,
@@ -3213,7 +4427,7 @@ function createMetaWhatsAppModule(params) {
3213
4427
  takeover: new TakeoverConversationUseCase(sessionRepository, providers.realtime, hooks),
3214
4428
  release: new ReleaseConversationUseCase(sessionRepository, providers.realtime, hooks),
3215
4429
  // Marca o pedido de atendimento (fila "aguardando atendimento") e dispara `onHumanRequested`.
3216
- requestHuman: new RequestHumanConversationUseCase(sessionRepository, providers.realtime, hooks),
4430
+ requestHuman,
3217
4431
  list: new ListConversationsUseCase(sessionRepository),
3218
4432
  listMessages: new ListMessagesUseCase(sessionRepository, messageRepository),
3219
4433
  listDocuments,
@@ -3252,6 +4466,18 @@ function createMetaWhatsAppModule(params) {
3252
4466
  webhook: {
3253
4467
  receive: receiveWebhook,
3254
4468
  // GET de verificação da Meta — o host liga na sua rota e devolve o retorno como texto puro.
4469
+ /**
4470
+ * Comando do simulador (ponte do `conversations-ui`) → payload da Meta com o `phone_number_id`
4471
+ * DESTE módulo. Montar com o padrão do builder fazia o filtro de número descartar a entrega.
4472
+ * Quem assina e entrega em `receive` é a rota do host.
4473
+ */
4474
+ buildPreviewPayload: /* @__PURE__ */ __name((command, envelope) => buildPreviewInboundPayload(command, {
4475
+ ...config.wabaId ? {
4476
+ wabaId: config.wabaId
4477
+ } : {},
4478
+ ...envelope,
4479
+ phoneNumberId: config.phoneNumberId
4480
+ }), "buildPreviewPayload"),
3255
4481
  verifyChallenge: /* @__PURE__ */ __name((query) => verifyWebhookChallenge({
3256
4482
  ...query,
3257
4483
  expectedToken: config.webhookVerifyToken
@@ -3265,6 +4491,9 @@ function createMetaWhatsAppModule(params) {
3265
4491
  } : {},
3266
4492
  ...providers.realtime ? {
3267
4493
  realtime: providers.realtime
4494
+ } : {},
4495
+ ...flowRunner ? {
4496
+ flowRunner
3268
4497
  } : {}
3269
4498
  }), hooks)
3270
4499
  },
@@ -3272,6 +4501,12 @@ function createMetaWhatsAppModule(params) {
3272
4501
  flows: flowInterpreter ? {
3273
4502
  interpreter: flowInterpreter,
3274
4503
  registerFlowAction: /* @__PURE__ */ __name((kind, handler) => flowInterpreter.registerFlowAction(kind, handler), "registerFlowAction"),
4504
+ // undefined quando `features.flowRunner` está desligado — o host dirige a conversa.
4505
+ runner: flowRunner,
4506
+ registerDynamicChoiceProvider: /* @__PURE__ */ __name((key, provider) => {
4507
+ if (!flowRunner) throw new ConfigMissingError2("features.flowRunner");
4508
+ flowRunner.registerDynamicChoiceProvider(key, provider);
4509
+ }, "registerDynamicChoiceProvider"),
3275
4510
  get: new GetFlowGraphUseCase(flowGraphRepository),
3276
4511
  list: new ListFlowGraphsUseCase(flowGraphRepository),
3277
4512
  create: new CreateFlowGraphUseCase(flowGraphRepository),
@@ -3398,18 +4633,26 @@ export {
3398
4633
  CreateFlowGraphUseCase,
3399
4634
  DEFAULT_FALLBACK_LIST_LABEL,
3400
4635
  DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
4636
+ DEFAULT_FLOW_TEXT,
4637
+ DEFAULT_MAX_INVALID_ANSWERS,
4638
+ DEFAULT_START_FLOW_KEY,
4639
+ DYNAMIC_CHOICE_MORE_ID,
3401
4640
  DeleteConversationUseCase,
3402
4641
  DeleteFlowGraphUseCase,
3403
4642
  DocumentRepository,
3404
4643
  ExportConversationUseCase,
4644
+ FLOW_RUNTIME_CONTEXT_KEY,
3405
4645
  FlowGraphCache,
3406
4646
  FlowGraphRepository,
4647
+ FlowHandoff,
3407
4648
  FlowInterpreter,
3408
4649
  FlowMediaIdRepository,
3409
4650
  FlowMediaRepository,
4651
+ FlowRunner,
3410
4652
  GetFlowGraphUseCase,
3411
4653
  GetLiveFlowPositionsUseCase,
3412
4654
  INBOUND_LOCATION_CONTENT,
4655
+ InProcessFlowTurnLock,
3413
4656
  InboundEffectsDispatcher,
3414
4657
  IngestInboundMediaUseCase,
3415
4658
  InvalidFlowGraphError,
@@ -3424,6 +4667,7 @@ export {
3424
4667
  OptimisticLockError,
3425
4668
  PREVIEW_MEDIA_ID_PREFIX,
3426
4669
  PRODUCT_LIST_LIMIT,
4670
+ PostgresAdvisoryFlowTurnLock,
3427
4671
  ProcessInboundDispatchUseCase,
3428
4672
  PurgeExpiredDocumentsUseCase,
3429
4673
  ReceiveWebhookUseCase,
@@ -3443,6 +4687,7 @@ export {
3443
4687
  WEBHOOK_CLAIM_TTL_SECONDS,
3444
4688
  WEBHOOK_NONCE_TTL_SECONDS,
3445
4689
  WhatsAppChannelAdapter,
4690
+ buildFlowChoiceMessage,
3446
4691
  buildInboundJobId,
3447
4692
  claimWebhookDelivery,
3448
4693
  confirmWebhookDelivery,
@@ -3455,14 +4700,19 @@ export {
3455
4700
  flowGraphs,
3456
4701
  flowMedia,
3457
4702
  isAudioMimeType,
4703
+ isChoiceNode,
3458
4704
  isRetriableTranscriptionError,
3459
4705
  isUnsupportedTranscriptionError,
3460
4706
  issueSseTicket,
3461
4707
  messages,
3462
4708
  metaWhatsAppMigrationsFolder,
3463
4709
  metaWhatsAppSchema,
4710
+ readFlowInbound,
3464
4711
  redeemSseTicket,
3465
4712
  resolveFailureStatus,
4713
+ resolveFlowAnswer,
4714
+ resolveFlowConfigText,
4715
+ resolveFlowTimeZone,
3466
4716
  resolvePreviewUploadId,
3467
4717
  runMetaWhatsAppMigrations,
3468
4718
  sessions,