@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.cjs CHANGED
@@ -8,11 +8,11 @@ var __export = (target, all) => {
8
8
  for (var name in all)
9
9
  __defProp(target, name, { get: all[name], enumerable: true });
10
10
  };
11
- var __copyProps = (to, from, except, desc3) => {
11
+ var __copyProps = (to, from, except, desc4) => {
12
12
  if (from && typeof from === "object" || typeof from === "function") {
13
13
  for (let key of __getOwnPropNames(from))
14
14
  if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc3 = __getOwnPropDesc(from, key)) || desc3.enumerable });
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc4 = __getOwnPropDesc(from, key)) || desc4.enumerable });
16
16
  }
17
17
  return to;
18
18
  };
@@ -25,18 +25,26 @@ __export(index_exports, {
25
25
  CreateFlowGraphUseCase: () => CreateFlowGraphUseCase,
26
26
  DEFAULT_FALLBACK_LIST_LABEL: () => DEFAULT_FALLBACK_LIST_LABEL,
27
27
  DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS: () => DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
28
+ DEFAULT_FLOW_TEXT: () => DEFAULT_FLOW_TEXT,
29
+ DEFAULT_MAX_INVALID_ANSWERS: () => DEFAULT_MAX_INVALID_ANSWERS,
30
+ DEFAULT_START_FLOW_KEY: () => DEFAULT_START_FLOW_KEY,
31
+ DYNAMIC_CHOICE_MORE_ID: () => DYNAMIC_CHOICE_MORE_ID,
28
32
  DeleteConversationUseCase: () => DeleteConversationUseCase,
29
33
  DeleteFlowGraphUseCase: () => DeleteFlowGraphUseCase,
30
34
  DocumentRepository: () => DocumentRepository,
31
35
  ExportConversationUseCase: () => ExportConversationUseCase,
36
+ FLOW_RUNTIME_CONTEXT_KEY: () => FLOW_RUNTIME_CONTEXT_KEY,
32
37
  FlowGraphCache: () => FlowGraphCache,
33
38
  FlowGraphRepository: () => FlowGraphRepository,
39
+ FlowHandoff: () => FlowHandoff,
34
40
  FlowInterpreter: () => FlowInterpreter,
35
41
  FlowMediaIdRepository: () => FlowMediaIdRepository,
36
42
  FlowMediaRepository: () => FlowMediaRepository,
43
+ FlowRunner: () => FlowRunner,
37
44
  GetFlowGraphUseCase: () => GetFlowGraphUseCase,
38
45
  GetLiveFlowPositionsUseCase: () => GetLiveFlowPositionsUseCase,
39
46
  INBOUND_LOCATION_CONTENT: () => INBOUND_LOCATION_CONTENT,
47
+ InProcessFlowTurnLock: () => InProcessFlowTurnLock,
40
48
  InboundEffectsDispatcher: () => InboundEffectsDispatcher,
41
49
  IngestInboundMediaUseCase: () => IngestInboundMediaUseCase,
42
50
  InvalidFlowGraphError: () => InvalidFlowGraphError,
@@ -49,8 +57,9 @@ __export(index_exports, {
49
57
  META_WHATSAPP_MIGRATIONS_TABLE: () => META_WHATSAPP_MIGRATIONS_TABLE,
50
58
  MessageRepository: () => MessageRepository,
51
59
  OptimisticLockError: () => OptimisticLockError,
52
- PREVIEW_MEDIA_ID_PREFIX: () => import_meta_whatsapp_contracts9.PREVIEW_MEDIA_ID_PREFIX,
60
+ PREVIEW_MEDIA_ID_PREFIX: () => import_meta_whatsapp_contracts15.PREVIEW_MEDIA_ID_PREFIX,
53
61
  PRODUCT_LIST_LIMIT: () => PRODUCT_LIST_LIMIT,
62
+ PostgresAdvisoryFlowTurnLock: () => PostgresAdvisoryFlowTurnLock,
54
63
  ProcessInboundDispatchUseCase: () => ProcessInboundDispatchUseCase,
55
64
  PurgeExpiredDocumentsUseCase: () => PurgeExpiredDocumentsUseCase,
56
65
  ReceiveWebhookUseCase: () => ReceiveWebhookUseCase,
@@ -70,6 +79,7 @@ __export(index_exports, {
70
79
  WEBHOOK_CLAIM_TTL_SECONDS: () => import_meta_graph_core3.WEBHOOK_CLAIM_TTL_SECONDS,
71
80
  WEBHOOK_NONCE_TTL_SECONDS: () => import_meta_graph_core3.WEBHOOK_NONCE_TTL_SECONDS,
72
81
  WhatsAppChannelAdapter: () => WhatsAppChannelAdapter,
82
+ buildFlowChoiceMessage: () => buildFlowChoiceMessage,
73
83
  buildInboundJobId: () => buildInboundJobId,
74
84
  claimWebhookDelivery: () => claimWebhookDelivery,
75
85
  confirmWebhookDelivery: () => confirmWebhookDelivery,
@@ -82,19 +92,24 @@ __export(index_exports, {
82
92
  flowGraphs: () => flowGraphs,
83
93
  flowMedia: () => flowMedia,
84
94
  isAudioMimeType: () => isAudioMimeType,
95
+ isChoiceNode: () => isChoiceNode,
85
96
  isRetriableTranscriptionError: () => isRetriableTranscriptionError,
86
97
  isUnsupportedTranscriptionError: () => isUnsupportedTranscriptionError,
87
98
  issueSseTicket: () => issueSseTicket,
88
99
  messages: () => messages,
89
100
  metaWhatsAppMigrationsFolder: () => metaWhatsAppMigrationsFolder,
90
101
  metaWhatsAppSchema: () => metaWhatsAppSchema,
102
+ readFlowInbound: () => readFlowInbound,
91
103
  redeemSseTicket: () => redeemSseTicket,
92
104
  resolveFailureStatus: () => resolveFailureStatus,
93
- resolvePreviewUploadId: () => import_meta_whatsapp_contracts9.resolvePreviewUploadId,
105
+ resolveFlowAnswer: () => resolveFlowAnswer,
106
+ resolveFlowConfigText: () => resolveFlowConfigText,
107
+ resolveFlowTimeZone: () => resolveFlowTimeZone,
108
+ resolvePreviewUploadId: () => import_meta_whatsapp_contracts15.resolvePreviewUploadId,
94
109
  runMetaWhatsAppMigrations: () => runMetaWhatsAppMigrations,
95
110
  sessions: () => sessions,
96
111
  settings: () => settings,
97
- toPreviewMediaId: () => import_meta_whatsapp_contracts9.toPreviewMediaId,
112
+ toPreviewMediaId: () => import_meta_whatsapp_contracts15.toPreviewMediaId,
98
113
  toSessionContract: () => toSessionContract,
99
114
  transcriptionRetryAfterSeconds: () => transcriptionRetryAfterSeconds,
100
115
  verifyWebhookChallenge: () => verifyWebhookChallenge,
@@ -104,7 +119,8 @@ module.exports = __toCommonJS(index_exports);
104
119
 
105
120
  // src/createMetaWhatsAppModule.ts
106
121
  var import_meta_whatsapp_provider = require("@adatechnology/meta-whatsapp-provider");
107
- var import_meta_whatsapp_contracts14 = require("@adatechnology/meta-whatsapp-contracts");
122
+ var import_testing = require("@adatechnology/meta-whatsapp-contracts/testing");
123
+ var import_meta_whatsapp_contracts20 = require("@adatechnology/meta-whatsapp-contracts");
108
124
 
109
125
  // src/repositories/SessionRepository.ts
110
126
  var import_drizzle_orm2 = require("drizzle-orm");
@@ -493,6 +509,21 @@ var SessionRepository = class {
493
509
  updatedAt: import_drizzle_orm2.sql`now()`
494
510
  }).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(sessions.companyId, companyId), (0, import_drizzle_orm2.eq)(sessions.whatsappNumber, whatsappNumber)));
495
511
  }
512
+ /**
513
+ * Posição no grafo e contexto numa escrita só — é o que o runner grava a cada mensagem. Em duas
514
+ * escritas, uma falha no meio deixaria a conversa num nó novo com as respostas do anterior.
515
+ * Não toca em `currentState`, `mode` nem `humanRequestedAt`: uma ação de encaminhamento que rodou
516
+ * no mesmo passo já os mudou, e regravá-los desfaria isso.
517
+ */
518
+ async saveFlowProgress(companyId, whatsappNumber, progress) {
519
+ await this.db.update(sessions).set({
520
+ flowKey: progress.flowKey,
521
+ currentNodeId: progress.currentNodeId,
522
+ context: progress.context,
523
+ lastActivity: import_drizzle_orm2.sql`now()`,
524
+ updatedAt: import_drizzle_orm2.sql`now()`
525
+ }).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(sessions.companyId, companyId), (0, import_drizzle_orm2.eq)(sessions.whatsappNumber, whatsappNumber)));
526
+ }
496
527
  // Marca a chegada de uma mensagem DO CLIENTE. É este carimbo — e não lastActivity, que também
497
528
  // se move em ações do atendente/bot — que define a janela de 24h do WhatsApp: fora dela, só
498
529
  // template aprovado reabre a conversa (ver WindowExpiredError nos contracts).
@@ -798,7 +829,8 @@ var MessageRepository = class {
798
829
  (0, import_drizzle_orm3.eq)(messages.sessionId, params.sessionId)
799
830
  ];
800
831
  if (params.before) conditions.push((0, import_drizzle_orm3.lt)(messages.createdAt, new Date(params.before)));
801
- return this.db.select().from(messages).where((0, import_drizzle_orm3.and)(...conditions)).orderBy(messages.createdAt).limit(params.limit ?? DEFAULT_LIMIT2);
832
+ const newestFirst = await this.db.select().from(messages).where((0, import_drizzle_orm3.and)(...conditions)).orderBy((0, import_drizzle_orm3.desc)(messages.createdAt), (0, import_drizzle_orm3.desc)(messages.id)).limit(params.limit ?? DEFAULT_LIMIT2);
833
+ return newestFirst.reverse();
802
834
  }
803
835
  };
804
836
 
@@ -1081,6 +1113,7 @@ var LogMessageUseCase = class {
1081
1113
  await this.sessionRepository.touchInbound(params.companyId, params.whatsappNumber);
1082
1114
  }
1083
1115
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "message", {
1116
+ companyId: params.companyId,
1084
1117
  direction: params.direction,
1085
1118
  sender: params.sender
1086
1119
  });
@@ -1299,6 +1332,7 @@ var TakeoverConversationUseCase = class {
1299
1332
  async execute(params) {
1300
1333
  await this.sessionRepository.takeover(params.companyId, params.whatsappNumber, params.agentUserId);
1301
1334
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "mode-changed", {
1335
+ companyId: params.companyId,
1302
1336
  mode: "human",
1303
1337
  assignedUserId: params.agentUserId
1304
1338
  });
@@ -1331,6 +1365,7 @@ var ReleaseConversationUseCase = class {
1331
1365
  async execute(params) {
1332
1366
  await this.sessionRepository.release(params.companyId, params.whatsappNumber);
1333
1367
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "mode-changed", {
1368
+ companyId: params.companyId,
1334
1369
  mode: "bot",
1335
1370
  assignedUserId: null
1336
1371
  });
@@ -1376,13 +1411,6 @@ function toSessionContract(row) {
1376
1411
  };
1377
1412
  }
1378
1413
  __name(toSessionContract, "toSessionContract");
1379
- function extractAnswer(message) {
1380
- const interactive = message.interactive;
1381
- if (interactive?.button_reply) return interactive.button_reply.id;
1382
- if (interactive?.list_reply) return interactive.list_reply.id;
1383
- return message.text?.body;
1384
- }
1385
- __name(extractAnswer, "extractAnswer");
1386
1414
  var InboundEffectsDispatcher = class {
1387
1415
  static {
1388
1416
  __name(this, "InboundEffectsDispatcher");
@@ -1416,7 +1444,13 @@ var InboundEffectsDispatcher = class {
1416
1444
  profileName: job.profileName
1417
1445
  });
1418
1446
  if (outcome?.outcome === "handled") return;
1419
- void extractAnswer(message);
1447
+ await this.params.flowRunner?.handle({
1448
+ companyId,
1449
+ message,
1450
+ ...job.profileName === void 0 ? {} : {
1451
+ profileName: job.profileName
1452
+ }
1453
+ });
1420
1454
  }
1421
1455
  async runStatusEffects(job) {
1422
1456
  const sessionRow = await this.params.sessionRepository.getContext(job.companyId, job.whatsappNumber);
@@ -1478,6 +1512,7 @@ var RequestHumanConversationUseCase = class {
1478
1512
  const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
1479
1513
  if (!session) throw new import_meta_whatsapp_contracts3.SessionNotFoundError(params.whatsappNumber);
1480
1514
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "human-requested", {
1515
+ companyId: params.companyId,
1481
1516
  humanRequestedAt: session.humanRequestedAt?.toISOString() ?? null
1482
1517
  });
1483
1518
  this.realtime?.emit("global", "data-changed", {});
@@ -2037,6 +2072,7 @@ var FlowInterpreter = class {
2037
2072
  return this.moveTo(input, resolveNext(node, branch));
2038
2073
  }
2039
2074
  if (node.type === "action") {
2075
+ if (!node.actionKind) return this.moveTo(input, resolveNext(node, void 0));
2040
2076
  const handler = node.actionKind ? this.actionHandlers.get(node.actionKind) : void 0;
2041
2077
  if (!handler) return {
2042
2078
  kind: "terminal",
@@ -2058,7 +2094,7 @@ var FlowInterpreter = class {
2058
2094
  context: contextAfterAction
2059
2095
  }, nextNodeId2);
2060
2096
  }
2061
- const isChoice = node.type === "menu" || node.questionType === "choice";
2097
+ const isChoice = node.type === "menu" || node.type === "dynamic_choice" || node.questionType === "choice";
2062
2098
  if (input.userAnswer === void 0) {
2063
2099
  return {
2064
2100
  kind: "awaiting-answer",
@@ -2066,9 +2102,10 @@ var FlowInterpreter = class {
2066
2102
  context: input.context
2067
2103
  };
2068
2104
  }
2105
+ const storedValue = input.answerValue !== void 0 ? input.answerValue : input.userAnswer;
2069
2106
  const updatedContext = node.contextKey ? {
2070
2107
  ...input.context,
2071
- [node.contextKey]: input.userAnswer
2108
+ [node.contextKey]: storedValue
2072
2109
  } : input.context;
2073
2110
  const answerId = isChoice ? input.userAnswer : void 0;
2074
2111
  const nextNodeId = resolveNext(node, answerId);
@@ -2111,6 +2148,8 @@ var FlowInterpreter = class {
2111
2148
  const visited = [
2112
2149
  input.currentNodeId
2113
2150
  ];
2151
+ const initialNode = input.graph.nodes[input.currentNodeId];
2152
+ if (options?.enterInitialNode && initialNode) await options.onNodeEntered?.(initialNode, input.context);
2114
2153
  let current = input;
2115
2154
  let steps = 0;
2116
2155
  while (steps < maxSteps) {
@@ -2122,11 +2161,14 @@ var FlowInterpreter = class {
2122
2161
  steps
2123
2162
  };
2124
2163
  visited.push(result.nodeId);
2164
+ const enteredNode = current.graph.nodes[result.nodeId];
2165
+ if (enteredNode) await options?.onNodeEntered?.(enteredNode, result.context);
2125
2166
  current = {
2126
2167
  ...current,
2127
2168
  currentNodeId: result.nodeId,
2128
2169
  context: result.context,
2129
- userAnswer: void 0
2170
+ userAnswer: void 0,
2171
+ answerValue: void 0
2130
2172
  };
2131
2173
  }
2132
2174
  return {
@@ -2138,6 +2180,1120 @@ var FlowInterpreter = class {
2138
2180
  }
2139
2181
  };
2140
2182
 
2183
+ // src/flows/FlowRunner.ts
2184
+ var import_meta_whatsapp_contracts13 = require("@adatechnology/meta-whatsapp-contracts");
2185
+
2186
+ // src/flows/resolveFlowAnswer.ts
2187
+ var import_meta_whatsapp_contracts9 = require("@adatechnology/meta-whatsapp-contracts");
2188
+
2189
+ // src/flows/flowRunner.constant.ts
2190
+ var DEFAULT_START_FLOW_KEY = "main";
2191
+ var DEFAULT_MAX_INVALID_ANSWERS = 2;
2192
+ var DEFAULT_MAX_CROSS_FLOW_JUMPS = 5;
2193
+ var DEFAULT_FLOW_TEXT = {
2194
+ FALLBACK: "N\xE3o entendi. Pode responder de novo?",
2195
+ CHOICE_PROMPT: "Escolha uma op\xE7\xE3o:",
2196
+ LIST_BUTTON_LABEL: "Ver op\xE7\xF5es",
2197
+ SEE_MORE: "Ver mais",
2198
+ NON_TEXT_ANSWER: "Por aqui eu entendo s\xF3 texto. Pode escrever a resposta?",
2199
+ MORE_OPTIONS_TRUNCATED: "\u2026",
2200
+ HANDOFF: "Vou chamar uma pessoa da equipe para continuar por aqui.",
2201
+ HANDOFF_OUT_OF_HOURS: "Nossa equipe est\xE1 fora do hor\xE1rio agora. Sua mensagem ficou registrada e respondemos assim que voltarmos."
2202
+ };
2203
+ var DYNAMIC_CHOICE_MORE_ID = "__more__";
2204
+ var FLOW_RUNTIME_CONTEXT_KEY = "__flow";
2205
+
2206
+ // src/flows/resolveFlowAnswer.ts
2207
+ function isChoiceNode(node) {
2208
+ return node.type === "menu" || node.questionType === "choice";
2209
+ }
2210
+ __name(isChoiceNode, "isChoiceNode");
2211
+ function keywordRoute(node, answer, isInteractiveReply) {
2212
+ if (isInteractiveReply || typeof node.next !== "object" || !node.next.byKeyword) return void 0;
2213
+ return (0, import_meta_whatsapp_contracts9.matchFlowKeywordRoute)(answer, node.next.byKeyword);
2214
+ }
2215
+ __name(keywordRoute, "keywordRoute");
2216
+ function matchOption(answer, options, isInteractiveReply) {
2217
+ if (isInteractiveReply) return options.some(([id]) => id === answer) ? answer : void 0;
2218
+ return (0, import_meta_whatsapp_contracts9.matchFlowChoice)(answer, options);
2219
+ }
2220
+ __name(matchOption, "matchOption");
2221
+ function resolveChoice(params, answer) {
2222
+ const optionId = matchOption(answer, params.options ?? params.node.options ?? [], params.isInteractiveReply);
2223
+ if (optionId) return {
2224
+ kind: "answer",
2225
+ userAnswer: optionId
2226
+ };
2227
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2228
+ return target ? {
2229
+ kind: "jump",
2230
+ target
2231
+ } : {
2232
+ kind: "invalid"
2233
+ };
2234
+ }
2235
+ __name(resolveChoice, "resolveChoice");
2236
+ function resolveDynamicChoice(params, answer) {
2237
+ const optionId = matchOption(answer, params.dynamicOptions ?? [], params.isInteractiveReply);
2238
+ if (optionId === DYNAMIC_CHOICE_MORE_ID) return {
2239
+ kind: "see-more"
2240
+ };
2241
+ if (optionId) return {
2242
+ kind: "answer",
2243
+ userAnswer: optionId
2244
+ };
2245
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2246
+ return target ? {
2247
+ kind: "jump",
2248
+ target
2249
+ } : {
2250
+ kind: "invalid"
2251
+ };
2252
+ }
2253
+ __name(resolveDynamicChoice, "resolveDynamicChoice");
2254
+ function resolveQuestion(params, answer) {
2255
+ const target = keywordRoute(params.node, answer, params.isInteractiveReply);
2256
+ if (target) return {
2257
+ kind: "jump",
2258
+ target
2259
+ };
2260
+ const result = (0, import_meta_whatsapp_contracts9.validateFlowAnswer)({
2261
+ node: params.node,
2262
+ answer,
2263
+ context: params.context,
2264
+ clock: params.clock
2265
+ });
2266
+ if (!result.isValid) return {
2267
+ kind: "invalid",
2268
+ rejection: result.rejection
2269
+ };
2270
+ return {
2271
+ kind: "answer",
2272
+ userAnswer: answer,
2273
+ value: result.value
2274
+ };
2275
+ }
2276
+ __name(resolveQuestion, "resolveQuestion");
2277
+ function resolveFlowAnswer(params) {
2278
+ if (params.answer === void 0) return {
2279
+ kind: "invalid"
2280
+ };
2281
+ if (params.node.type === "dynamic_choice") return resolveDynamicChoice(params, params.answer);
2282
+ if (isChoiceNode(params.node)) return resolveChoice(params, params.answer);
2283
+ return resolveQuestion(params, params.answer);
2284
+ }
2285
+ __name(resolveFlowAnswer, "resolveFlowAnswer");
2286
+
2287
+ // src/flows/FlowQuestionRenderer.ts
2288
+ var import_meta_whatsapp_contracts11 = require("@adatechnology/meta-whatsapp-contracts");
2289
+
2290
+ // src/flows/buildFlowChoiceMessage.ts
2291
+ var import_meta_whatsapp_contracts10 = require("@adatechnology/meta-whatsapp-contracts");
2292
+ function groupSections(options) {
2293
+ const sections = [];
2294
+ for (const option of options) {
2295
+ const title = option.section?.trim() || void 0;
2296
+ const existing = sections.find((section) => section.title === title);
2297
+ if (existing) existing.rows.push(option);
2298
+ else sections.push({
2299
+ title,
2300
+ rows: [
2301
+ option
2302
+ ]
2303
+ });
2304
+ }
2305
+ return sections.map((section) => ({
2306
+ ...section.title ? {
2307
+ title: section.title
2308
+ } : {},
2309
+ rows: section.rows.map((row) => ({
2310
+ id: row.id,
2311
+ title: row.title,
2312
+ ...row.description ? {
2313
+ description: row.description
2314
+ } : {}
2315
+ }))
2316
+ }));
2317
+ }
2318
+ __name(groupSections, "groupSections");
2319
+ function asNumberedText(params) {
2320
+ const lines = params.options.map((option, index2) => {
2321
+ const description = option.description ? ` \u2014 ${option.description}` : "";
2322
+ return `${index2 + 1}. ${option.title}${description}`;
2323
+ });
2324
+ const limit = import_meta_whatsapp_contracts10.WHATSAPP_CHOICE_LIMIT.TEXT_BODY_LENGTH;
2325
+ const full = `${params.body}
2326
+
2327
+ ${lines.join("\n")}`;
2328
+ if (Array.from(full).length <= limit) return {
2329
+ kind: "text",
2330
+ body: full
2331
+ };
2332
+ const truncated = `
2333
+ ${DEFAULT_FLOW_TEXT.MORE_OPTIONS_TRUNCATED}`;
2334
+ let body = `${params.body}
2335
+ `;
2336
+ for (const line of lines) {
2337
+ const candidate = `${body}
2338
+ ${line}`;
2339
+ if (Array.from(candidate).length + truncated.length > limit) break;
2340
+ body = candidate;
2341
+ }
2342
+ const withMarker = `${body}${truncated}`;
2343
+ return {
2344
+ kind: "text",
2345
+ body: Array.from(withMarker).slice(0, limit).join("")
2346
+ };
2347
+ }
2348
+ __name(asNumberedText, "asNumberedText");
2349
+ function buildFlowChoiceMessage(params) {
2350
+ const isPlain = params.options.every((option) => !option.description && !option.section);
2351
+ if (isPlain && params.options.length <= import_meta_whatsapp_contracts10.WHATSAPP_CHOICE_LIMIT.BUTTONS) {
2352
+ const buttons = {
2353
+ kind: "buttons",
2354
+ body: params.body,
2355
+ buttons: params.options.map((option) => ({
2356
+ id: option.id,
2357
+ title: option.title
2358
+ }))
2359
+ };
2360
+ if ((0, import_meta_whatsapp_contracts10.listInteractiveLimitViolations)(buttons).length === 0) return {
2361
+ kind: "interactive",
2362
+ interactive: buttons
2363
+ };
2364
+ }
2365
+ const list = {
2366
+ kind: "list",
2367
+ body: params.body,
2368
+ buttonLabel: params.listButtonLabel,
2369
+ sections: groupSections(params.options)
2370
+ };
2371
+ if ((0, import_meta_whatsapp_contracts10.listInteractiveLimitViolations)(list).length === 0) return {
2372
+ kind: "interactive",
2373
+ interactive: list
2374
+ };
2375
+ return asNumberedText(params);
2376
+ }
2377
+ __name(buildFlowChoiceMessage, "buildFlowChoiceMessage");
2378
+
2379
+ // src/flows/flowRuntimeState.ts
2380
+ function runtimeOf(context) {
2381
+ const state = context[FLOW_RUNTIME_CONTEXT_KEY];
2382
+ return state !== null && typeof state === "object" ? state : {};
2383
+ }
2384
+ __name(runtimeOf, "runtimeOf");
2385
+ function withRuntime(context, state) {
2386
+ return {
2387
+ ...context,
2388
+ [FLOW_RUNTIME_CONTEXT_KEY]: state
2389
+ };
2390
+ }
2391
+ __name(withRuntime, "withRuntime");
2392
+
2393
+ // src/flows/FlowQuestionRenderer.ts
2394
+ var FlowQuestionRenderer = class {
2395
+ static {
2396
+ __name(this, "FlowQuestionRenderer");
2397
+ }
2398
+ config;
2399
+ providers = /* @__PURE__ */ new Map();
2400
+ constructor(config) {
2401
+ this.config = config;
2402
+ for (const [key, provider] of Object.entries(config.dynamicChoiceProviders ?? {})) this.providers.set(key, provider);
2403
+ }
2404
+ registerDynamicChoiceProvider(key, provider) {
2405
+ this.providers.set(key, provider);
2406
+ }
2407
+ interpolate(text2, variables) {
2408
+ return (0, import_meta_whatsapp_contracts11.interpolateFlowText)(text2, variables, this.config.formatValue ? {
2409
+ formatValue: this.config.formatValue
2410
+ } : {});
2411
+ }
2412
+ async prepare(params) {
2413
+ const { node, context } = params;
2414
+ const variables = {
2415
+ ...context,
2416
+ ...params.variables
2417
+ };
2418
+ const body = this.interpolate(node.question ?? this.config.choicePrompt ?? DEFAULT_FLOW_TEXT.CHOICE_PROMPT, variables);
2419
+ const listButtonLabel = node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL;
2420
+ if (node.type === "dynamic_choice") {
2421
+ const options = await this.loadDynamicOptions(params);
2422
+ const shown = options.map((option) => [
2423
+ option.id,
2424
+ option.title
2425
+ ]);
2426
+ const state = {
2427
+ ...runtimeOf(context),
2428
+ dynamic: {
2429
+ nodeId: node.id,
2430
+ page: params.page,
2431
+ options: shown
2432
+ }
2433
+ };
2434
+ return {
2435
+ message: buildFlowChoiceMessage({
2436
+ body,
2437
+ options,
2438
+ listButtonLabel
2439
+ }),
2440
+ context: withRuntime(context, state)
2441
+ };
2442
+ }
2443
+ if (isChoiceNode(node) && (node.options?.length ?? 0) > 0) {
2444
+ const options = (node.options ?? []).map(([id, title]) => {
2445
+ const detail = node.optionDetails?.[id];
2446
+ return {
2447
+ id,
2448
+ title: this.interpolate(title, variables),
2449
+ ...detail?.description ? {
2450
+ description: this.interpolate(detail.description, variables)
2451
+ } : {},
2452
+ ...detail?.section ? {
2453
+ section: detail.section
2454
+ } : {}
2455
+ };
2456
+ });
2457
+ return {
2458
+ message: buildFlowChoiceMessage({
2459
+ body,
2460
+ options,
2461
+ listButtonLabel
2462
+ }),
2463
+ context
2464
+ };
2465
+ }
2466
+ if (!node.question) return {
2467
+ context
2468
+ };
2469
+ return {
2470
+ message: {
2471
+ kind: "text",
2472
+ body
2473
+ },
2474
+ context
2475
+ };
2476
+ }
2477
+ async loadDynamicOptions(params) {
2478
+ const { node } = params;
2479
+ const provider = node.choiceProvider ? this.providers.get(node.choiceProvider) : void 0;
2480
+ if (!provider) throw new import_meta_whatsapp_contracts11.FlowRunnerError("provider-missing", node.choiceProvider ?? node.id);
2481
+ const pageSize = import_meta_whatsapp_contracts11.WHATSAPP_CHOICE_LIMIT.LIST_ROWS - 1;
2482
+ const result = await provider({
2483
+ node,
2484
+ session: params.session,
2485
+ context: params.context,
2486
+ page: params.page,
2487
+ pageSize
2488
+ });
2489
+ const options = result.options.slice(0, pageSize).map((option) => ({
2490
+ id: option.id,
2491
+ title: option.title,
2492
+ ...option.description ? {
2493
+ description: option.description
2494
+ } : {}
2495
+ }));
2496
+ const seeMore = this.config.seeMoreLabel ?? DEFAULT_FLOW_TEXT.SEE_MORE;
2497
+ return result.hasMore ? [
2498
+ ...options,
2499
+ {
2500
+ id: DYNAMIC_CHOICE_MORE_ID,
2501
+ title: seeMore
2502
+ }
2503
+ ] : options;
2504
+ }
2505
+ };
2506
+
2507
+ // src/flows/readFlowInbound.ts
2508
+ function readFlowInbound(message) {
2509
+ const reply = message.interactive?.button_reply?.id ?? message.interactive?.list_reply?.id;
2510
+ if (reply !== void 0) return {
2511
+ kind: "reply",
2512
+ answer: reply
2513
+ };
2514
+ if (message.text?.body !== void 0) return {
2515
+ kind: "text",
2516
+ answer: message.text.body
2517
+ };
2518
+ if (message.button?.text !== void 0) return {
2519
+ kind: "text",
2520
+ answer: message.button.text
2521
+ };
2522
+ return {
2523
+ kind: "unsupported"
2524
+ };
2525
+ }
2526
+ __name(readFlowInbound, "readFlowInbound");
2527
+
2528
+ // src/flows/matchGlobalKeyword.ts
2529
+ var import_meta_whatsapp_contracts12 = require("@adatechnology/meta-whatsapp-contracts");
2530
+ function matchGlobalKeyword(text2, entries) {
2531
+ const normalized = (0, import_meta_whatsapp_contracts12.normalizeFlowText)(text2);
2532
+ if (normalized.length === 0) return void 0;
2533
+ const padded = ` ${normalized} `;
2534
+ let best;
2535
+ for (const entry of entries) {
2536
+ const isWordMatch = entry.match === "word";
2537
+ for (const keyword of entry.keywords) {
2538
+ const normalizedKeyword = (0, import_meta_whatsapp_contracts12.normalizeFlowText)(keyword);
2539
+ if (normalizedKeyword.length === 0) continue;
2540
+ const isMatch = isWordMatch ? padded.includes(` ${normalizedKeyword} `) : normalizedKeyword === normalized;
2541
+ if (isMatch && (!best || normalizedKeyword.length > best.length)) {
2542
+ best = {
2543
+ length: normalizedKeyword.length,
2544
+ target: entry.target
2545
+ };
2546
+ }
2547
+ }
2548
+ }
2549
+ return best?.target;
2550
+ }
2551
+ __name(matchGlobalKeyword, "matchGlobalKeyword");
2552
+
2553
+ // src/flows/resolveFlowConfigText.ts
2554
+ async function resolveOne(text2, params) {
2555
+ if (typeof text2 !== "function") return text2;
2556
+ try {
2557
+ return await text2(params.context);
2558
+ } catch (error) {
2559
+ await params.onError?.(error);
2560
+ return void 0;
2561
+ }
2562
+ }
2563
+ __name(resolveOne, "resolveOne");
2564
+ async function resolveFlowConfigText(params) {
2565
+ for (const text2 of params.chain) {
2566
+ const resolved = await resolveOne(text2, params);
2567
+ if (resolved !== void 0) return resolved;
2568
+ }
2569
+ return void 0;
2570
+ }
2571
+ __name(resolveFlowConfigText, "resolveFlowConfigText");
2572
+
2573
+ // src/flows/FlowRunner.ts
2574
+ function contactVariables(profileName) {
2575
+ if (!profileName) return {};
2576
+ return {
2577
+ contactName: profileName,
2578
+ contactFirstName: profileName.trim().split(/\s+/)[0] ?? profileName
2579
+ };
2580
+ }
2581
+ __name(contactVariables, "contactVariables");
2582
+ function resolveFlowTimeZone(config) {
2583
+ const businessHours = config.handoff?.businessHours;
2584
+ const timeZone = config.timeZone ?? (typeof businessHours === "object" ? businessHours.timeZone : void 0);
2585
+ if (!timeZone) throw new import_meta_whatsapp_contracts13.ConfigMissingError("features.flowRunner.timeZone");
2586
+ new Intl.DateTimeFormat("en-US", {
2587
+ timeZone
2588
+ });
2589
+ return timeZone;
2590
+ }
2591
+ __name(resolveFlowTimeZone, "resolveFlowTimeZone");
2592
+ var FlowRunner = class {
2593
+ static {
2594
+ __name(this, "FlowRunner");
2595
+ }
2596
+ dependencies;
2597
+ renderer;
2598
+ timeZone;
2599
+ // Variáveis da mensagem em curso, por sessão: é como a action `handoff` (que só recebe a sessão)
2600
+ // enxerga o nome do contato sem que ele precise ir para o contexto gravado.
2601
+ turnVariables = /* @__PURE__ */ new WeakMap();
2602
+ constructor(dependencies) {
2603
+ this.dependencies = dependencies;
2604
+ this.renderer = new FlowQuestionRenderer(dependencies.config);
2605
+ this.timeZone = resolveFlowTimeZone(dependencies.config);
2606
+ }
2607
+ registerDynamicChoiceProvider(key, provider) {
2608
+ this.renderer.registerDynamicChoiceProvider(key, provider);
2609
+ }
2610
+ /**
2611
+ * Variáveis para `{{chave}}`. As do host (`resolveVariables`, `contactName`, `contactFirstName`)
2612
+ * vencem as respostas do cliente: um `contextKey` chamado `contactName` não pode trocar o nome que
2613
+ * o sistema conhece pelo que o cliente digitou.
2614
+ */
2615
+ variablesFor(params) {
2616
+ return {
2617
+ ...params.context,
2618
+ ...this.turnVariables.get(params.session) ?? {}
2619
+ };
2620
+ }
2621
+ /** Atende uma mensagem. Um turno por conversa de cada vez (`lock`); reentrega da mesma mensagem é ignorada. */
2622
+ handle(params) {
2623
+ const key = {
2624
+ companyId: params.companyId,
2625
+ whatsappNumber: params.message.from
2626
+ };
2627
+ return this.dependencies.lock.withLock(key, () => this.handleLocked(params));
2628
+ }
2629
+ /** Abre um fluxo para a conversa sem esperar mensagem — ex.: ao devolver a conversa ao bot. */
2630
+ start(params) {
2631
+ const key = {
2632
+ companyId: params.companyId,
2633
+ whatsappNumber: params.whatsappNumber
2634
+ };
2635
+ return this.dependencies.lock.withLock(key, async () => {
2636
+ const row = await this.dependencies.sessionRepository.getContext(params.companyId, params.whatsappNumber);
2637
+ if (!row) return "no-session";
2638
+ const turn = await this.openTurn({
2639
+ companyId: params.companyId,
2640
+ session: toSessionContract(row),
2641
+ ...params.profileName ? {
2642
+ profileName: params.profileName
2643
+ } : {}
2644
+ });
2645
+ const graph = await this.loadGraph(params.companyId, params.flowKey ?? this.startFlowKey());
2646
+ if (!graph) return "no-flow";
2647
+ turn.isClaimed = true;
2648
+ return this.guard(turn, async () => {
2649
+ await this.runFrom(turn, {
2650
+ graph,
2651
+ nodeId: graph.startNodeId,
2652
+ context: {
2653
+ ...turn.session.context
2654
+ },
2655
+ enterInitialNode: true
2656
+ });
2657
+ return "handled";
2658
+ });
2659
+ });
2660
+ }
2661
+ async handleLocked(params) {
2662
+ const row = await this.dependencies.sessionRepository.getContext(params.companyId, params.message.from);
2663
+ if (!row) return "no-session";
2664
+ if (row.mode === "human") return "human-mode";
2665
+ const session = toSessionContract(row);
2666
+ if (runtimeOf(session.context).lastInboundId === params.message.id) return "duplicate";
2667
+ const turn = await this.openTurn({
2668
+ companyId: params.companyId,
2669
+ session,
2670
+ inboundId: params.message.id,
2671
+ ...params.profileName ? {
2672
+ profileName: params.profileName
2673
+ } : {}
2674
+ });
2675
+ return this.guard(turn, () => this.route(turn, readFlowInbound(params.message)));
2676
+ }
2677
+ async route(turn, inbound) {
2678
+ const globalTarget = inbound.kind === "text" ? this.globalKeywordTarget(inbound.answer) : void 0;
2679
+ if (globalTarget) return this.applyGlobalTarget(turn, globalTarget);
2680
+ const whileAwaitingHuman = this.dependencies.config.whileAwaitingHuman ?? "silent";
2681
+ if (turn.session.humanRequestedAt && !turn.session.currentNodeId && whileAwaitingHuman === "silent") {
2682
+ return "awaiting-human";
2683
+ }
2684
+ const savedFlowKey = turn.session.flowKey;
2685
+ const savedGraph = await this.loadGraph(turn.companyId, savedFlowKey ?? this.startFlowKey());
2686
+ const isStale = !savedGraph && savedFlowKey !== null && savedFlowKey !== this.startFlowKey();
2687
+ const graph = savedGraph ?? (isStale ? await this.loadGraph(turn.companyId, this.startFlowKey()) : void 0);
2688
+ if (!graph) return "no-flow";
2689
+ await this.claim(turn);
2690
+ if (isStale) await this.report(turn, savedFlowKey, turn.session.currentNodeId, "cross-flow", new import_meta_whatsapp_contracts13.FlowRunnerError("flow-not-found", savedFlowKey));
2691
+ const node = !isStale && turn.session.currentNodeId ? graph.nodes[turn.session.currentNodeId] : void 0;
2692
+ const context = {
2693
+ ...turn.session.context
2694
+ };
2695
+ if (node) {
2696
+ await this.answerNode({
2697
+ turn,
2698
+ graph,
2699
+ node,
2700
+ context,
2701
+ inbound
2702
+ });
2703
+ return "handled";
2704
+ }
2705
+ const start = graph.nodes[graph.startNodeId];
2706
+ const target = start && inbound.kind !== "unsupported" ? this.keywordJumpAtStart(start, inbound) : void 0;
2707
+ if (target) await this.jumpTo(turn, graph, target, context);
2708
+ else await this.runFrom(turn, {
2709
+ graph,
2710
+ nodeId: graph.startNodeId,
2711
+ context,
2712
+ enterInitialNode: true
2713
+ });
2714
+ return "handled";
2715
+ }
2716
+ async guard(turn, work) {
2717
+ try {
2718
+ return await work();
2719
+ } catch (error) {
2720
+ if (!turn.isClaimed) throw error;
2721
+ await this.report(turn, turn.session.flowKey, turn.session.currentNodeId, "turn", error);
2722
+ return "handled";
2723
+ }
2724
+ }
2725
+ /** Primeira escrita do turno: grava o id da mensagem antes de qualquer efeito externo. */
2726
+ async claim(turn) {
2727
+ if (turn.isClaimed) return;
2728
+ await this.save(turn, {
2729
+ flowKey: turn.session.flowKey,
2730
+ nodeId: turn.session.currentNodeId,
2731
+ context: {
2732
+ ...turn.session.context
2733
+ }
2734
+ });
2735
+ turn.isClaimed = true;
2736
+ }
2737
+ async openTurn(params) {
2738
+ const { session, profileName } = params;
2739
+ const resolver = this.dependencies.config.resolveVariables;
2740
+ const hostVariables = resolver ? await resolver({
2741
+ session,
2742
+ ...profileName ? {
2743
+ profileName
2744
+ } : {}
2745
+ }) : {};
2746
+ const baseVariables = {
2747
+ ...contactVariables(profileName),
2748
+ ...hostVariables
2749
+ };
2750
+ this.turnVariables.set(session, baseVariables);
2751
+ return {
2752
+ companyId: params.companyId,
2753
+ session,
2754
+ baseVariables,
2755
+ ...params.inboundId ? {
2756
+ inboundId: params.inboundId
2757
+ } : {},
2758
+ isClaimed: false
2759
+ };
2760
+ }
2761
+ startFlowKey() {
2762
+ return this.dependencies.config.startFlowKey ?? DEFAULT_START_FLOW_KEY;
2763
+ }
2764
+ clock() {
2765
+ const { config } = this.dependencies;
2766
+ return {
2767
+ now: config.now?.() ?? /* @__PURE__ */ new Date(),
2768
+ locale: config.dateLocale ?? import_meta_whatsapp_contracts13.FLOW_DATE_LOCALE_PT_BR,
2769
+ timeZone: this.timeZone
2770
+ };
2771
+ }
2772
+ loadGraph(companyId, flowKey) {
2773
+ return this.dependencies.flowGraphRepository.get(companyId, flowKey);
2774
+ }
2775
+ globalKeywordTarget(answer) {
2776
+ return matchGlobalKeyword(answer, this.dependencies.config.globalKeywords ?? []);
2777
+ }
2778
+ keywordJumpAtStart(start, inbound) {
2779
+ if (inbound.kind === "unsupported") return void 0;
2780
+ const decision = resolveFlowAnswer({
2781
+ node: start,
2782
+ answer: inbound.answer,
2783
+ isInteractiveReply: inbound.kind === "reply",
2784
+ context: {},
2785
+ clock: this.clock()
2786
+ });
2787
+ return decision.kind === "jump" ? decision.target : void 0;
2788
+ }
2789
+ /**
2790
+ * Palavra global vale mesmo com a conversa aguardando atendimento. Reiniciar NÃO tira o pedido da
2791
+ * fila (`humanRequestedAt` continua): a equipe ainda responde, e o cliente pode usar o bot enquanto
2792
+ * espera; quando o fluxo terminar, o runner volta ao silêncio.
2793
+ */
2794
+ async applyGlobalTarget(turn, target) {
2795
+ const context = withRuntime({
2796
+ ...turn.session.context
2797
+ }, {});
2798
+ if (target === "handoff") {
2799
+ await this.claim(turn);
2800
+ await this.handOff(turn, context);
2801
+ return "handled";
2802
+ }
2803
+ const flowKey = target === "restart" ? this.startFlowKey() : (0, import_meta_whatsapp_contracts13.crossFlowKey)(target);
2804
+ const graph = await this.loadGraph(turn.companyId, flowKey);
2805
+ if (!graph) return "no-flow";
2806
+ await this.claim(turn);
2807
+ await this.runFrom(turn, {
2808
+ graph,
2809
+ nodeId: graph.startNodeId,
2810
+ context,
2811
+ enterInitialNode: true
2812
+ });
2813
+ return "handled";
2814
+ }
2815
+ async answerNode(params) {
2816
+ const { turn, graph, node, context, inbound } = params;
2817
+ const runtime = runtimeOf(context);
2818
+ const dynamic = runtime.dynamic?.nodeId === node.id ? runtime.dynamic : void 0;
2819
+ const page = dynamic?.page ?? 0;
2820
+ if (inbound.kind === "unsupported") {
2821
+ const text2 = await this.configText(turn, node, {
2822
+ chain: [
2823
+ this.dependencies.config.nonTextAnswerMessage
2824
+ ],
2825
+ kind: "non-text-answer"
2826
+ });
2827
+ await this.say(turn, text2 ?? DEFAULT_FLOW_TEXT.NON_TEXT_ANSWER, context);
2828
+ return this.awaitAnswer(turn, graph, node, context, page);
2829
+ }
2830
+ const decision = resolveFlowAnswer({
2831
+ node,
2832
+ answer: inbound.answer,
2833
+ isInteractiveReply: inbound.kind === "reply",
2834
+ context,
2835
+ clock: this.clock(),
2836
+ ...dynamic ? {
2837
+ dynamicOptions: dynamic.options
2838
+ } : {},
2839
+ ...isChoiceNode(node) ? {
2840
+ options: this.renderedOptions(turn, node, context)
2841
+ } : {}
2842
+ });
2843
+ if (decision.kind === "jump") return this.jumpTo(turn, graph, decision.target, withRuntime(context, {}));
2844
+ if (decision.kind === "see-more") return this.awaitAnswer(turn, graph, node, context, page + 1);
2845
+ if (decision.kind === "invalid" && this.followsDefaultWhenUnmatched(node)) {
2846
+ return this.runFrom(turn, {
2847
+ graph,
2848
+ nodeId: node.id,
2849
+ context: withRuntime(context, {}),
2850
+ userAnswer: inbound.answer,
2851
+ enterInitialNode: false
2852
+ });
2853
+ }
2854
+ if (decision.kind === "invalid") {
2855
+ return this.handleInvalid(turn, graph, node, context, {
2856
+ rejection: decision.rejection
2857
+ });
2858
+ }
2859
+ const hostRejection = await this.validateWithHost(turn, node, context, {
2860
+ answer: inbound.answer,
2861
+ value: decision.value
2862
+ });
2863
+ if (hostRejection) return this.handleInvalid(turn, graph, node, context, hostRejection);
2864
+ await this.runFrom(turn, {
2865
+ graph,
2866
+ nodeId: node.id,
2867
+ context: withRuntime(context, {}),
2868
+ userAnswer: decision.userAnswer,
2869
+ ...decision.value !== void 0 ? {
2870
+ answerValue: decision.value
2871
+ } : {},
2872
+ enterInitialNode: false
2873
+ });
2874
+ }
2875
+ /** Títulos como o cliente os viu (`{{chave}}` resolvido): é contra eles que o texto digitado casa. */
2876
+ renderedOptions(turn, node, context) {
2877
+ const variables = {
2878
+ ...context,
2879
+ ...turn.baseVariables
2880
+ };
2881
+ return (node.options ?? []).map(([id, title]) => [
2882
+ id,
2883
+ this.renderer.interpolate(title, variables)
2884
+ ]);
2885
+ }
2886
+ /**
2887
+ * Validador do host, só para pergunta (escolha já casou com opção) e nunca para resposta pulada.
2888
+ * Falha do validador não pode prender o cliente na pergunta: reporta e aceita.
2889
+ */
2890
+ async validateWithHost(turn, node, context, answer) {
2891
+ const validator = this.dependencies.config.validateAnswer;
2892
+ if (!validator || isChoiceNode(node) || node.type === "dynamic_choice" || answer.value === null) return void 0;
2893
+ try {
2894
+ const result = await validator({
2895
+ companyId: turn.companyId,
2896
+ session: turn.session,
2897
+ node,
2898
+ answer: answer.answer.trim(),
2899
+ value: answer.value ?? answer.answer,
2900
+ context
2901
+ });
2902
+ if (!result || result.isValid) return void 0;
2903
+ return {
2904
+ rejection: "rejected-by-host",
2905
+ ...result.message ? {
2906
+ message: result.message
2907
+ } : {}
2908
+ };
2909
+ } catch (error) {
2910
+ await this.report(turn, turn.session.flowKey, node.id, "validate-answer", error);
2911
+ return void 0;
2912
+ }
2913
+ }
2914
+ configText(turn, node, params) {
2915
+ return resolveFlowConfigText({
2916
+ chain: params.chain,
2917
+ context: {
2918
+ companyId: turn.companyId,
2919
+ whatsappNumber: turn.session.whatsappNumber,
2920
+ kind: params.kind,
2921
+ flowKey: turn.session.flowKey,
2922
+ ...node ? {
2923
+ nodeId: node.id
2924
+ } : {},
2925
+ ...params.rejection ? {
2926
+ rejection: params.rejection
2927
+ } : {}
2928
+ },
2929
+ onError: /* @__PURE__ */ __name((error) => this.report(turn, turn.session.flowKey, node?.id ?? null, "text", error), "onError")
2930
+ });
2931
+ }
2932
+ followsDefaultWhenUnmatched(node) {
2933
+ if (!isChoiceNode(node)) return false;
2934
+ return (node.unmatchedChoice ?? this.dependencies.config.unmatchedChoice ?? "reask") === "default";
2935
+ }
2936
+ async handleInvalid(turn, graph, node, context, invalid) {
2937
+ const runtime = runtimeOf(context);
2938
+ const attempts = (runtime.invalidAnswers ?? 0) + 1;
2939
+ const limit = node.maxInvalidAnswers ?? this.dependencies.config.maxInvalidAnswers ?? DEFAULT_MAX_INVALID_ANSWERS;
2940
+ if (attempts >= limit) return this.handOff(turn, withRuntime(context, {}));
2941
+ const updated = withRuntime(context, {
2942
+ ...runtime,
2943
+ invalidAnswers: attempts
2944
+ });
2945
+ await this.say(turn, await this.fallbackText(turn, node, invalid), updated);
2946
+ await this.awaitAnswer(turn, graph, node, updated, runtime.dynamic?.nodeId === node.id ? runtime.dynamic.page : 0);
2947
+ }
2948
+ /** Precedência: texto do validador do host, `fallbackMessage` do nó, texto do motivo, padrão do host, do pacote. */
2949
+ async fallbackText(turn, node, invalid) {
2950
+ const { config } = this.dependencies;
2951
+ const fixed = invalid.message ?? node.fallbackMessage;
2952
+ if (fixed !== void 0) return fixed;
2953
+ const { rejection } = invalid;
2954
+ const byRejection = rejection ? await this.configText(turn, node, {
2955
+ chain: [
2956
+ config.rejectionMessages?.[rejection]
2957
+ ],
2958
+ kind: "rejection",
2959
+ rejection
2960
+ }) : void 0;
2961
+ if (byRejection !== void 0) return byRejection;
2962
+ const fallback = await this.configText(turn, node, {
2963
+ chain: [
2964
+ config.defaultFallbackMessage
2965
+ ],
2966
+ kind: "fallback"
2967
+ });
2968
+ return fallback ?? DEFAULT_FLOW_TEXT.FALLBACK;
2969
+ }
2970
+ async handOff(turn, context) {
2971
+ const isWithinHours = await this.dependencies.handoff.request({
2972
+ companyId: turn.companyId,
2973
+ whatsappNumber: turn.session.whatsappNumber,
2974
+ variables: {
2975
+ ...context,
2976
+ ...turn.baseVariables
2977
+ }
2978
+ });
2979
+ await this.save(turn, {
2980
+ flowKey: null,
2981
+ nodeId: null,
2982
+ context: {
2983
+ ...context,
2984
+ handoffWithinBusinessHours: isWithinHours
2985
+ }
2986
+ });
2987
+ }
2988
+ async jumpTo(turn, graph, target, context) {
2989
+ if ((0, import_meta_whatsapp_contracts13.isCrossFlowTarget)(target)) {
2990
+ const targetGraph = await this.loadGraph(turn.companyId, (0, import_meta_whatsapp_contracts13.crossFlowKey)(target));
2991
+ if (!targetGraph) return this.reportMissingFlow(turn, graph.key, target, context);
2992
+ return this.runFrom(turn, {
2993
+ graph: targetGraph,
2994
+ nodeId: targetGraph.startNodeId,
2995
+ context,
2996
+ enterInitialNode: true
2997
+ });
2998
+ }
2999
+ return this.runFrom(turn, {
3000
+ graph,
3001
+ nodeId: target,
3002
+ context,
3003
+ enterInitialNode: true
3004
+ });
3005
+ }
3006
+ async runFrom(turn, initial) {
3007
+ const maxJumps = this.dependencies.config.maxCrossFlowJumps ?? DEFAULT_MAX_CROSS_FLOW_JUMPS;
3008
+ let params = initial;
3009
+ for (let jump = 0; jump <= maxJumps; jump++) {
3010
+ const result = await this.dependencies.interpreter.run({
3011
+ graph: params.graph,
3012
+ currentNodeId: params.nodeId,
3013
+ ...params.userAnswer !== void 0 ? {
3014
+ userAnswer: params.userAnswer
3015
+ } : {},
3016
+ ...params.answerValue !== void 0 ? {
3017
+ answerValue: params.answerValue
3018
+ } : {},
3019
+ context: params.context,
3020
+ session: turn.session,
3021
+ channel: this.dependencies.channel
3022
+ }, {
3023
+ enterInitialNode: params.enterInitialNode,
3024
+ onNodeEntered: /* @__PURE__ */ __name(async (node, context) => {
3025
+ if (node.directMessage) await this.say(turn, node.directMessage, context);
3026
+ }, "onNodeEntered")
3027
+ });
3028
+ if (result.kind === "awaiting-answer") {
3029
+ const node = params.graph.nodes[result.nodeId];
3030
+ if (node) return this.awaitAnswer(turn, params.graph, node, result.context, 0);
3031
+ return this.save(turn, {
3032
+ flowKey: null,
3033
+ nodeId: null,
3034
+ context: result.context
3035
+ });
3036
+ }
3037
+ if (result.kind === "terminal") return this.save(turn, {
3038
+ flowKey: null,
3039
+ nodeId: null,
3040
+ context: result.context
3041
+ });
3042
+ if (result.kind === "max-steps-exceeded") {
3043
+ await this.save(turn, {
3044
+ flowKey: null,
3045
+ nodeId: null,
3046
+ context: result.context
3047
+ });
3048
+ return this.report(turn, params.graph.key, null, "max-steps", new import_meta_whatsapp_contracts13.FlowRunnerError("cycle", result.visited.join(" -> ")));
3049
+ }
3050
+ const target = await this.loadGraph(turn.companyId, result.flowKey);
3051
+ if (!target) return this.reportMissingFlow(turn, params.graph.key, result.flowKey, result.context);
3052
+ params = {
3053
+ graph: target,
3054
+ nodeId: target.startNodeId,
3055
+ context: result.context,
3056
+ enterInitialNode: true
3057
+ };
3058
+ }
3059
+ await this.save(turn, {
3060
+ flowKey: null,
3061
+ nodeId: null,
3062
+ context: params.context
3063
+ });
3064
+ return this.report(turn, params.graph.key, null, "cross-flow", new import_meta_whatsapp_contracts13.FlowRunnerError("too-many-jumps", params.graph.key));
3065
+ }
3066
+ /** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
3067
+ async awaitAnswer(turn, graph, node, context, page) {
3068
+ try {
3069
+ const { message, context: renderedContext } = await this.renderer.prepare({
3070
+ session: turn.session,
3071
+ variables: turn.baseVariables,
3072
+ node,
3073
+ context,
3074
+ page
3075
+ });
3076
+ await this.save(turn, {
3077
+ flowKey: graph.key,
3078
+ nodeId: node.id,
3079
+ context: renderedContext
3080
+ });
3081
+ if (message) await this.send(turn, message);
3082
+ } catch (error) {
3083
+ await this.report(turn, graph.key, node.id, "render", error);
3084
+ }
3085
+ }
3086
+ async say(turn, template, context) {
3087
+ const body = this.renderer.interpolate(template, {
3088
+ ...context,
3089
+ ...turn.baseVariables
3090
+ });
3091
+ if (body.trim().length > 0) await this.send(turn, {
3092
+ kind: "text",
3093
+ body
3094
+ });
3095
+ }
3096
+ async send(turn, message) {
3097
+ const common = {
3098
+ companyId: turn.companyId,
3099
+ whatsappNumber: turn.session.whatsappNumber,
3100
+ sender: "bot",
3101
+ startState: this.dependencies.startState
3102
+ };
3103
+ if (message.kind === "text") await this.dependencies.sendMessage.sendText({
3104
+ ...common,
3105
+ body: message.body
3106
+ });
3107
+ else await this.dependencies.sendMessage.sendInteractive({
3108
+ ...common,
3109
+ interactive: message.interactive
3110
+ });
3111
+ }
3112
+ save(turn, progress) {
3113
+ const runtime = runtimeOf(progress.context);
3114
+ const context = turn.inboundId ? withRuntime(progress.context, {
3115
+ ...runtime,
3116
+ lastInboundId: turn.inboundId
3117
+ }) : progress.context;
3118
+ return this.dependencies.sessionRepository.saveFlowProgress(turn.companyId, turn.session.whatsappNumber, {
3119
+ flowKey: progress.flowKey,
3120
+ currentNodeId: progress.nodeId,
3121
+ context
3122
+ });
3123
+ }
3124
+ async reportMissingFlow(turn, fromFlowKey, target, context) {
3125
+ await this.save(turn, {
3126
+ flowKey: null,
3127
+ nodeId: null,
3128
+ context
3129
+ });
3130
+ await this.report(turn, fromFlowKey, null, "cross-flow", new import_meta_whatsapp_contracts13.FlowRunnerError("flow-not-found", target));
3131
+ }
3132
+ /**
3133
+ * Nunca relança: só é chamado depois de o turno ter sido gravado, e relançar faria a fila repetir
3134
+ * uma mensagem já marcada como tratada. Sem gancho, o erro é descartado (a conversa fica no último
3135
+ * ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
3136
+ */
3137
+ async report(turn, flowKey, nodeId, stage, error) {
3138
+ const details = {
3139
+ companyId: turn.companyId,
3140
+ whatsappNumber: turn.session.whatsappNumber,
3141
+ flowKey,
3142
+ nodeId,
3143
+ stage
3144
+ };
3145
+ try {
3146
+ await this.dependencies.hooks?.onFlowRunnerError?.(error, details);
3147
+ } catch {
3148
+ }
3149
+ }
3150
+ };
3151
+
3152
+ // src/flows/FlowHandoff.ts
3153
+ var import_meta_whatsapp_contracts14 = require("@adatechnology/meta-whatsapp-contracts");
3154
+ function readParam(node, key) {
3155
+ const value = node?.actionParams?.[key];
3156
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
3157
+ }
3158
+ __name(readParam, "readParam");
3159
+ var FlowHandoff = class {
3160
+ static {
3161
+ __name(this, "FlowHandoff");
3162
+ }
3163
+ dependencies;
3164
+ constructor(dependencies) {
3165
+ this.dependencies = dependencies;
3166
+ }
3167
+ /** Devolve se caiu dentro do horário — vai para o contexto como `handoffWithinBusinessHours`. */
3168
+ async request(params) {
3169
+ const { requestHuman, sendMessage, startState, interpolation } = this.dependencies;
3170
+ try {
3171
+ await requestHuman.execute({
3172
+ companyId: params.companyId,
3173
+ whatsappNumber: params.whatsappNumber
3174
+ });
3175
+ } catch (error) {
3176
+ await this.reportFailure(error, params, "handoff");
3177
+ }
3178
+ const isWithinHours = await this.isWithinHours(params.companyId);
3179
+ const template = await this.messageFor(isWithinHours, params);
3180
+ await sendMessage.sendText({
3181
+ companyId: params.companyId,
3182
+ whatsappNumber: params.whatsappNumber,
3183
+ body: (0, import_meta_whatsapp_contracts14.interpolateFlowText)(template, params.variables, interpolation),
3184
+ sender: "bot",
3185
+ startState
3186
+ });
3187
+ return isWithinHours;
3188
+ }
3189
+ /**
3190
+ * Handler do `actionKind: 'handoff'`. `actionParams.message` e `actionParams.outOfHoursMessage`
3191
+ * sobrescrevem os textos do runner para aquele nó.
3192
+ */
3193
+ createActionHandler(resolveVariables) {
3194
+ return async ({ node, session, context }) => {
3195
+ const isWithinHours = await this.request({
3196
+ companyId: session.companyId,
3197
+ whatsappNumber: session.whatsappNumber,
3198
+ variables: resolveVariables({
3199
+ session,
3200
+ context
3201
+ }),
3202
+ node
3203
+ });
3204
+ return {
3205
+ context: {
3206
+ handoffWithinBusinessHours: isWithinHours
3207
+ }
3208
+ };
3209
+ };
3210
+ }
3211
+ async reportFailure(error, params, stage) {
3212
+ try {
3213
+ await this.dependencies.hooks?.onFlowRunnerError?.(error, {
3214
+ companyId: params.companyId,
3215
+ whatsappNumber: params.whatsappNumber,
3216
+ flowKey: null,
3217
+ nodeId: params.node?.id ?? null,
3218
+ stage
3219
+ });
3220
+ } catch {
3221
+ }
3222
+ }
3223
+ async isWithinHours(companyId) {
3224
+ const source = this.dependencies.config.businessHours;
3225
+ const hours = typeof source === "function" ? await source(companyId) : source;
3226
+ return hours ? (0, import_meta_whatsapp_contracts14.isWithinBusinessHours)(hours, this.dependencies.now()) : true;
3227
+ }
3228
+ async messageFor(isWithinHours, params) {
3229
+ const { config } = this.dependencies;
3230
+ const { node } = params;
3231
+ const chain = isWithinHours ? [
3232
+ readParam(node, "message"),
3233
+ config.message,
3234
+ DEFAULT_FLOW_TEXT.HANDOFF
3235
+ ] : [
3236
+ readParam(node, "outOfHoursMessage"),
3237
+ config.outOfHoursMessage,
3238
+ readParam(node, "message"),
3239
+ config.message,
3240
+ DEFAULT_FLOW_TEXT.HANDOFF_OUT_OF_HOURS
3241
+ ];
3242
+ const text2 = await resolveFlowConfigText({
3243
+ chain,
3244
+ context: {
3245
+ companyId: params.companyId,
3246
+ whatsappNumber: params.whatsappNumber,
3247
+ kind: isWithinHours ? "handoff" : "handoff-out-of-hours",
3248
+ ...node ? {
3249
+ nodeId: node.id
3250
+ } : {}
3251
+ },
3252
+ onError: /* @__PURE__ */ __name((error) => this.reportFailure(error, params, "text"), "onError")
3253
+ });
3254
+ return text2 ?? DEFAULT_FLOW_TEXT.HANDOFF;
3255
+ }
3256
+ };
3257
+
3258
+ // src/flows/flowTurnLock.ts
3259
+ var import_drizzle_orm7 = require("drizzle-orm");
3260
+ function lockName(key) {
3261
+ return `meta_whatsapp_flow:${key.companyId}:${key.whatsappNumber}`;
3262
+ }
3263
+ __name(lockName, "lockName");
3264
+ var PostgresAdvisoryFlowTurnLock = class {
3265
+ static {
3266
+ __name(this, "PostgresAdvisoryFlowTurnLock");
3267
+ }
3268
+ db;
3269
+ constructor(db) {
3270
+ this.db = db;
3271
+ }
3272
+ withLock(key, work) {
3273
+ return this.db.transaction(async (transaction) => {
3274
+ await transaction.execute(import_drizzle_orm7.sql`select pg_advisory_xact_lock(hashtext(${lockName(key)}))`);
3275
+ return work();
3276
+ });
3277
+ }
3278
+ };
3279
+ var InProcessFlowTurnLock = class {
3280
+ static {
3281
+ __name(this, "InProcessFlowTurnLock");
3282
+ }
3283
+ tails = /* @__PURE__ */ new Map();
3284
+ async withLock(key, work) {
3285
+ const name = lockName(key);
3286
+ const previous = this.tails.get(name) ?? Promise.resolve();
3287
+ const current = previous.catch(() => void 0).then(work);
3288
+ this.tails.set(name, current);
3289
+ try {
3290
+ return await current;
3291
+ } finally {
3292
+ if (this.tails.get(name) === current) this.tails.delete(name);
3293
+ }
3294
+ }
3295
+ };
3296
+
2141
3297
  // src/flows/createSendMediaAction.ts
2142
3298
  function mediaTypeFor2(mimeType) {
2143
3299
  if (mimeType.startsWith("image/")) return "image";
@@ -2303,7 +3459,7 @@ async function listAvailableProducts(params) {
2303
3459
  __name(listAvailableProducts, "listAvailableProducts");
2304
3460
 
2305
3461
  // src/repositories/FlowMediaRepository.ts
2306
- var import_drizzle_orm7 = require("drizzle-orm");
3462
+ var import_drizzle_orm8 = require("drizzle-orm");
2307
3463
  var FlowMediaRepository = class {
2308
3464
  static {
2309
3465
  __name(this, "FlowMediaRepository");
@@ -2313,18 +3469,18 @@ var FlowMediaRepository = class {
2313
3469
  this.db = db;
2314
3470
  }
2315
3471
  locationFilter(location) {
2316
- return (0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(flowMedia.companyId, location.companyId), (0, import_drizzle_orm7.eq)(flowMedia.flowKey, location.flowKey), (0, import_drizzle_orm7.eq)(flowMedia.nodeId, location.nodeId));
3472
+ return (0, import_drizzle_orm8.and)((0, import_drizzle_orm8.eq)(flowMedia.companyId, location.companyId), (0, import_drizzle_orm8.eq)(flowMedia.flowKey, location.flowKey), (0, import_drizzle_orm8.eq)(flowMedia.nodeId, location.nodeId));
2317
3473
  }
2318
3474
  // O que o nó realmente envia, na ordem de envio. `active` filtrado aqui e não no chamador:
2319
3475
  // é a razão de a coluna existir, e um chamador que esquecesse do filtro mandaria ao cliente
2320
3476
  // justamente o material que alguém desligou.
2321
3477
  async listActive(location) {
2322
- return this.db.select().from(flowMedia).where((0, import_drizzle_orm7.and)(this.locationFilter(location), (0, import_drizzle_orm7.eq)(flowMedia.active, true))).orderBy((0, import_drizzle_orm7.asc)(flowMedia.sortOrder), (0, import_drizzle_orm7.asc)(flowMedia.createdAt));
3478
+ return this.db.select().from(flowMedia).where((0, import_drizzle_orm8.and)(this.locationFilter(location), (0, import_drizzle_orm8.eq)(flowMedia.active, true))).orderBy((0, import_drizzle_orm8.asc)(flowMedia.sortOrder), (0, import_drizzle_orm8.asc)(flowMedia.createdAt));
2323
3479
  }
2324
3480
  // Inclui os desligados — é a visão do editor, onde desligar precisa continuar visível para
2325
3481
  // poder ser religado.
2326
3482
  async listAll(location) {
2327
- return this.db.select().from(flowMedia).where(this.locationFilter(location)).orderBy((0, import_drizzle_orm7.asc)(flowMedia.sortOrder), (0, import_drizzle_orm7.asc)(flowMedia.createdAt));
3483
+ return this.db.select().from(flowMedia).where(this.locationFilter(location)).orderBy((0, import_drizzle_orm8.asc)(flowMedia.sortOrder), (0, import_drizzle_orm8.asc)(flowMedia.createdAt));
2328
3484
  }
2329
3485
  /**
2330
3486
  * Anexa um arquivo já existente no storage ao nó.
@@ -2355,7 +3511,7 @@ var FlowMediaRepository = class {
2355
3511
  caption: params.caption ?? null,
2356
3512
  sortOrder: params.sortOrder ?? 0,
2357
3513
  active: true,
2358
- updatedAt: import_drizzle_orm7.sql`now()`
3514
+ updatedAt: import_drizzle_orm8.sql`now()`
2359
3515
  }
2360
3516
  }).returning();
2361
3517
  return row;
@@ -2371,8 +3527,8 @@ var FlowMediaRepository = class {
2371
3527
  ...params.active !== void 0 ? {
2372
3528
  active: params.active
2373
3529
  } : {},
2374
- updatedAt: import_drizzle_orm7.sql`now()`
2375
- }).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm7.eq)(flowMedia.id, params.id))).returning();
3530
+ updatedAt: import_drizzle_orm8.sql`now()`
3531
+ }).where((0, import_drizzle_orm8.and)((0, import_drizzle_orm8.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm8.eq)(flowMedia.id, params.id))).returning();
2376
3532
  return row;
2377
3533
  }
2378
3534
  /**
@@ -2381,17 +3537,17 @@ var FlowMediaRepository = class {
2381
3537
  * host, que é dono da biblioteca de arquivos.
2382
3538
  */
2383
3539
  async detach(params) {
2384
- await this.db.delete(flowMedia).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm7.eq)(flowMedia.id, params.id)));
3540
+ await this.db.delete(flowMedia).where((0, import_drizzle_orm8.and)((0, import_drizzle_orm8.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm8.eq)(flowMedia.id, params.id)));
2385
3541
  }
2386
3542
  // Chamado ao salvar o grafo: nós apagados no editor deixam linhas que nada mais alcança.
2387
3543
  async detachRemovedNodes(params) {
2388
- const condition = params.existingNodeIds.length === 0 ? void 0 : import_drizzle_orm7.sql`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
2389
- await this.db.delete(flowMedia).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm7.eq)(flowMedia.flowKey, params.flowKey), condition));
3544
+ const condition = params.existingNodeIds.length === 0 ? void 0 : import_drizzle_orm8.sql`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
3545
+ await this.db.delete(flowMedia).where((0, import_drizzle_orm8.and)((0, import_drizzle_orm8.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm8.eq)(flowMedia.flowKey, params.flowKey), condition));
2390
3546
  }
2391
3547
  };
2392
3548
 
2393
3549
  // src/repositories/FlowMediaIdRepository.ts
2394
- var import_drizzle_orm8 = require("drizzle-orm");
3550
+ var import_drizzle_orm9 = require("drizzle-orm");
2395
3551
  var FlowMediaIdRepository = class {
2396
3552
  static {
2397
3553
  __name(this, "FlowMediaIdRepository");
@@ -2403,7 +3559,7 @@ var FlowMediaIdRepository = class {
2403
3559
  async get(params) {
2404
3560
  const rows = await this.db.select({
2405
3561
  ids: flowMedia.metaMediaIds
2406
- }).from(flowMedia).where((0, import_drizzle_orm8.eq)(flowMedia.id, params.flowMediaId)).limit(1);
3562
+ }).from(flowMedia).where((0, import_drizzle_orm9.eq)(flowMedia.id, params.flowMediaId)).limit(1);
2407
3563
  return rows[0]?.ids?.[params.senderKey];
2408
3564
  }
2409
3565
  /**
@@ -2415,23 +3571,23 @@ var FlowMediaIdRepository = class {
2415
3571
  */
2416
3572
  async set(params) {
2417
3573
  await this.db.update(flowMedia).set({
2418
- metaMediaIds: import_drizzle_orm8.sql`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
2419
- }).where((0, import_drizzle_orm8.eq)(flowMedia.id, params.flowMediaId));
3574
+ metaMediaIds: import_drizzle_orm9.sql`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
3575
+ }).where((0, import_drizzle_orm9.eq)(flowMedia.id, params.flowMediaId));
2420
3576
  }
2421
3577
  /** Remove só a chave deste número — o id do outro número continua válido. */
2422
3578
  async clear(params) {
2423
3579
  await this.db.update(flowMedia).set({
2424
- metaMediaIds: import_drizzle_orm8.sql`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
2425
- }).where((0, import_drizzle_orm8.eq)(flowMedia.id, params.flowMediaId));
3580
+ metaMediaIds: import_drizzle_orm9.sql`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
3581
+ }).where((0, import_drizzle_orm9.eq)(flowMedia.id, params.flowMediaId));
2426
3582
  }
2427
3583
  };
2428
3584
 
2429
3585
  // src/channel/WhatsAppChannelAdapter.ts
2430
3586
  var import_meta_graph_core2 = require("@adatechnology/meta-graph-core");
2431
- var import_meta_whatsapp_contracts10 = require("@adatechnology/meta-whatsapp-contracts");
3587
+ var import_meta_whatsapp_contracts16 = require("@adatechnology/meta-whatsapp-contracts");
2432
3588
 
2433
3589
  // src/channel/previewMedia.ts
2434
- var import_meta_whatsapp_contracts9 = require("@adatechnology/meta-whatsapp-contracts");
3590
+ var import_meta_whatsapp_contracts15 = require("@adatechnology/meta-whatsapp-contracts");
2435
3591
 
2436
3592
  // src/channel/WhatsAppChannelAdapter.ts
2437
3593
  var WhatsAppChannelAdapter = class {
@@ -2440,25 +3596,40 @@ var WhatsAppChannelAdapter = class {
2440
3596
  }
2441
3597
  messages;
2442
3598
  previewMedia;
2443
- constructor(messages2, previewMedia) {
3599
+ previewContacts;
3600
+ constructor(messages2, previewMedia, previewContacts) {
2444
3601
  this.messages = messages2;
2445
3602
  this.previewMedia = previewMedia;
3603
+ this.previewContacts = previewContacts;
3604
+ }
3605
+ /** `preview.<uuid>` quando o destino é contato do simulador e o recurso está ligado. */
3606
+ previewMessageId(to) {
3607
+ if (!this.previewContacts?.isEnabled || !(0, import_meta_whatsapp_contracts16.isPreviewContact)(to)) return void 0;
3608
+ return `preview.${this.previewContacts.generateId?.() ?? globalThis.crypto.randomUUID()}`;
2446
3609
  }
2447
3610
  async translateErrors(operation) {
2448
3611
  try {
2449
3612
  return await operation();
2450
3613
  } catch (error) {
2451
- if (error instanceof import_meta_graph_core2.WhatsAppWindowExpiredError) throw new import_meta_whatsapp_contracts10.WindowExpiredError();
3614
+ if (error instanceof import_meta_graph_core2.WhatsAppWindowExpiredError) throw new import_meta_whatsapp_contracts16.WindowExpiredError();
2452
3615
  throw error;
2453
3616
  }
2454
3617
  }
2455
3618
  async sendText(to, body) {
3619
+ const previewId = this.previewMessageId(to);
3620
+ if (previewId) return {
3621
+ externalMessageId: previewId
3622
+ };
2456
3623
  const result = await this.translateErrors(() => this.messages.sendText(to, body));
2457
3624
  return {
2458
3625
  externalMessageId: result.waMessageId
2459
3626
  };
2460
3627
  }
2461
3628
  async sendMedia(params) {
3629
+ const previewId = this.previewMessageId(params.to);
3630
+ if (previewId) return {
3631
+ externalMessageId: previewId
3632
+ };
2462
3633
  const result = await this.translateErrors(() => this.messages.sendMedia(params));
2463
3634
  return {
2464
3635
  externalMessageId: result.waMessageId,
@@ -2466,12 +3637,20 @@ var WhatsAppChannelAdapter = class {
2466
3637
  };
2467
3638
  }
2468
3639
  async sendTemplate(params) {
3640
+ const previewId = this.previewMessageId(params.to);
3641
+ if (previewId) return {
3642
+ externalMessageId: previewId
3643
+ };
2469
3644
  const result = await this.translateErrors(() => this.messages.sendTemplate(params));
2470
3645
  return {
2471
3646
  externalMessageId: result.waMessageId
2472
3647
  };
2473
3648
  }
2474
3649
  async sendInteractiveList(params) {
3650
+ const previewId = this.previewMessageId(params.to);
3651
+ if (previewId) return {
3652
+ externalMessageId: previewId
3653
+ };
2475
3654
  const sections = (params.sections ?? [
2476
3655
  {
2477
3656
  rows: params.rows ?? []
@@ -2497,6 +3676,10 @@ var WhatsAppChannelAdapter = class {
2497
3676
  };
2498
3677
  }
2499
3678
  async sendInteractiveButtons(params) {
3679
+ const previewId = this.previewMessageId(params.to);
3680
+ if (previewId) return {
3681
+ externalMessageId: previewId
3682
+ };
2500
3683
  const result = await this.translateErrors(() => this.messages.sendInteractiveButtons({
2501
3684
  to: params.to,
2502
3685
  bodyText: params.body,
@@ -2507,6 +3690,10 @@ var WhatsAppChannelAdapter = class {
2507
3690
  };
2508
3691
  }
2509
3692
  async sendProductList(params) {
3693
+ const previewId = this.previewMessageId(params.to);
3694
+ if (previewId) return {
3695
+ externalMessageId: previewId
3696
+ };
2510
3697
  const result = await this.translateErrors(() => this.messages.sendProductListMessage({
2511
3698
  to: params.to,
2512
3699
  headerText: params.headerText,
@@ -2527,7 +3714,7 @@ var WhatsAppChannelAdapter = class {
2527
3714
  * tentar buscá-lo lá renderia um 404 confuso em vez do áudio que o operador acabou de gravar.
2528
3715
  */
2529
3716
  async fetchMediaAsBase64(mediaId) {
2530
- const uploadId = this.previewMedia?.isEnabled ? (0, import_meta_whatsapp_contracts9.resolvePreviewUploadId)(mediaId) : void 0;
3717
+ const uploadId = this.previewMedia?.isEnabled ? (0, import_meta_whatsapp_contracts15.resolvePreviewUploadId)(mediaId) : void 0;
2531
3718
  if (uploadId) {
2532
3719
  const buffer = await this.previewMedia.objectStorage.getObject(uploadId);
2533
3720
  return {
@@ -2540,19 +3727,19 @@ var WhatsAppChannelAdapter = class {
2540
3727
  };
2541
3728
 
2542
3729
  // src/channel/ReceiveWebhook.use-case.ts
2543
- var import_meta_whatsapp_contracts13 = require("@adatechnology/meta-whatsapp-contracts");
3730
+ var import_meta_whatsapp_contracts19 = require("@adatechnology/meta-whatsapp-contracts");
2544
3731
 
2545
3732
  // src/channel/webhookSecurity.ts
2546
3733
  var import_meta_graph_core3 = require("@adatechnology/meta-graph-core");
2547
- var import_meta_whatsapp_contracts11 = require("@adatechnology/meta-whatsapp-contracts");
3734
+ var import_meta_whatsapp_contracts17 = require("@adatechnology/meta-whatsapp-contracts");
2548
3735
  var WEBHOOK_NONCE_NAMESPACE = "meta-whatsapp";
2549
3736
  function verifyWebhookChallenge(params) {
2550
- if (!(0, import_meta_graph_core3.isValidWebhookChallenge)(params)) throw new import_meta_whatsapp_contracts11.InvalidWebhookSignatureError();
3737
+ if (!(0, import_meta_graph_core3.isValidWebhookChallenge)(params)) throw new import_meta_whatsapp_contracts17.InvalidWebhookSignatureError();
2551
3738
  return params.challenge;
2552
3739
  }
2553
3740
  __name(verifyWebhookChallenge, "verifyWebhookChallenge");
2554
3741
  function verifyWebhookSignature(params) {
2555
- if (!(0, import_meta_graph_core3.isValidWebhookSignature)(params)) throw new import_meta_whatsapp_contracts11.InvalidWebhookSignatureError();
3742
+ if (!(0, import_meta_graph_core3.isValidWebhookSignature)(params)) throw new import_meta_whatsapp_contracts17.InvalidWebhookSignatureError();
2556
3743
  }
2557
3744
  __name(verifyWebhookSignature, "verifyWebhookSignature");
2558
3745
  function deliveryKey(signatureHeader) {
@@ -2572,10 +3759,10 @@ async function confirmWebhookDelivery(params) {
2572
3759
  __name(confirmWebhookDelivery, "confirmWebhookDelivery");
2573
3760
 
2574
3761
  // src/channel/IngestInboundMedia.use-case.ts
2575
- var import_drizzle_orm9 = require("drizzle-orm");
3762
+ var import_drizzle_orm10 = require("drizzle-orm");
2576
3763
 
2577
3764
  // src/use-cases/TranscribeAudio.use-case.ts
2578
- var import_meta_whatsapp_contracts12 = require("@adatechnology/meta-whatsapp-contracts");
3765
+ var import_meta_whatsapp_contracts18 = require("@adatechnology/meta-whatsapp-contracts");
2579
3766
 
2580
3767
  // src/transcription.types.ts
2581
3768
  var TRANSCRIPTION_STATUS = {
@@ -2636,7 +3823,7 @@ var TranscribeAudioUseCase = class {
2636
3823
  }
2637
3824
  if (this.dependencies.resolvePolicy) {
2638
3825
  const policy = await this.dependencies.resolvePolicy(params.companyId);
2639
- if (!policy.isEnabled) throw new import_meta_whatsapp_contracts12.TranscriptionDisabledError();
3826
+ if (!policy.isEnabled) throw new import_meta_whatsapp_contracts18.TranscriptionDisabledError();
2640
3827
  }
2641
3828
  const audio = extractAudioReference(message);
2642
3829
  const buffer = await this.dependencies.objectStorage.getObject(audio.uploadId);
@@ -2713,11 +3900,11 @@ function extractAudioReference(message) {
2713
3900
  const audio = payload["audio"];
2714
3901
  const mimeType = typeof payload["mimeType"] === "string" ? payload["mimeType"] : audio?.mime_type;
2715
3902
  if (!isAudioMimeType(mimeType) && !audio) {
2716
- throw new import_meta_whatsapp_contracts12.MessageNotAudioError(message.id, message.type);
3903
+ throw new import_meta_whatsapp_contracts18.MessageNotAudioError(message.id, message.type);
2717
3904
  }
2718
3905
  const uploadId = payload["uploadId"];
2719
3906
  if (typeof uploadId !== "string" || uploadId.length === 0) {
2720
- throw new import_meta_whatsapp_contracts12.AudioNotIngestedError(message.id);
3907
+ throw new import_meta_whatsapp_contracts18.AudioNotIngestedError(message.id);
2721
3908
  }
2722
3909
  return {
2723
3910
  uploadId,
@@ -2744,7 +3931,7 @@ var IngestInboundMediaUseCase = class {
2744
3931
  this.transcription = transcription;
2745
3932
  }
2746
3933
  async execute(params) {
2747
- const [message] = await this.db.select().from(messages).where((0, import_drizzle_orm9.and)((0, import_drizzle_orm9.eq)(messages.companyId, params.companyId), (0, import_drizzle_orm9.eq)(messages.id, params.messageId))).limit(1);
3934
+ const [message] = await this.db.select().from(messages).where((0, import_drizzle_orm10.and)((0, import_drizzle_orm10.eq)(messages.companyId, params.companyId), (0, import_drizzle_orm10.eq)(messages.id, params.messageId))).limit(1);
2748
3935
  if (!message) throw new Error(`Mensagem ${params.messageId} n\xE3o encontrada para ingest\xE3o de m\xEDdia`);
2749
3936
  const payload = message.payload ?? {};
2750
3937
  if (payload["uploadId"] && payload["sourceMediaId"] === params.sourceMediaId) {
@@ -2775,7 +3962,7 @@ var IngestInboundMediaUseCase = class {
2775
3962
  };
2776
3963
  await this.db.update(messages).set({
2777
3964
  payload: updatedPayload
2778
- }).where((0, import_drizzle_orm9.and)((0, import_drizzle_orm9.eq)(messages.companyId, params.companyId), (0, import_drizzle_orm9.eq)(messages.id, params.messageId)));
3965
+ }).where((0, import_drizzle_orm10.and)((0, import_drizzle_orm10.eq)(messages.companyId, params.companyId), (0, import_drizzle_orm10.eq)(messages.id, params.messageId)));
2779
3966
  await this.documentRepository?.link({
2780
3967
  companyId: params.companyId,
2781
3968
  sessionId: message.sessionId,
@@ -2933,8 +4120,8 @@ function extractPayload(message, { isLocationRedacted } = DEFAULT_EXTRACTION_OPT
2933
4120
  }
2934
4121
  __name(extractPayload, "extractPayload");
2935
4122
  var ACCOUNT_EVENT_FIELDS = [
2936
- import_meta_whatsapp_contracts13.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE,
2937
- import_meta_whatsapp_contracts13.WHATSAPP_WEBHOOK_FIELDS.PHONE_NUMBER_QUALITY_UPDATE
4123
+ import_meta_whatsapp_contracts19.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE,
4124
+ import_meta_whatsapp_contracts19.WHATSAPP_WEBHOOK_FIELDS.PHONE_NUMBER_QUALITY_UPDATE
2938
4125
  ];
2939
4126
  function isAccountEventField(field) {
2940
4127
  return field !== void 0 && ACCOUNT_EVENT_FIELDS.includes(field);
@@ -2954,6 +4141,9 @@ var ReceiveWebhookUseCase = class {
2954
4141
  } : {},
2955
4142
  ...params.realtime ? {
2956
4143
  realtime: params.realtime
4144
+ } : {},
4145
+ ...params.flowRunner ? {
4146
+ flowRunner: params.flowRunner
2957
4147
  } : {}
2958
4148
  });
2959
4149
  }
@@ -2973,7 +4163,7 @@ var ReceiveWebhookUseCase = class {
2973
4163
  ...EMPTY_RESULT
2974
4164
  };
2975
4165
  const rawText = typeof input.rawBody === "string" ? input.rawBody : input.rawBody.toString("utf8");
2976
- const parsed = import_meta_whatsapp_contracts13.whatsAppWebhookPayloadSchema.safeParse(JSON.parse(rawText));
4166
+ const parsed = import_meta_whatsapp_contracts19.whatsAppWebhookPayloadSchema.safeParse(JSON.parse(rawText));
2977
4167
  if (!parsed.success) {
2978
4168
  await this.params.hooks?.onUnhandledWebhookEvent?.({
2979
4169
  field: void 0,
@@ -3006,7 +4196,7 @@ var ReceiveWebhookUseCase = class {
3006
4196
  continue;
3007
4197
  }
3008
4198
  for (const message of change.value.messages ?? []) {
3009
- const profileName = (0, import_meta_whatsapp_contracts13.resolveContactProfileName)({
4199
+ const profileName = (0, import_meta_whatsapp_contracts19.resolveContactProfileName)({
3010
4200
  contacts: change.value.contacts,
3011
4201
  from: message.from
3012
4202
  });
@@ -3044,8 +4234,8 @@ var ReceiveWebhookUseCase = class {
3044
4234
  // Devolve `false` quando o corpo não bate com o schema do field — o chamador conta como não
3045
4235
  // tratado. O host é avisado nos dois casos, mas com `reason` diferente.
3046
4236
  async handleAccountEvent(change) {
3047
- if (change.field === import_meta_whatsapp_contracts13.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE) {
3048
- const update = import_meta_whatsapp_contracts13.whatsAppTemplateStatusUpdateSchema.safeParse(change.value);
4237
+ if (change.field === import_meta_whatsapp_contracts19.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE) {
4238
+ const update = import_meta_whatsapp_contracts19.whatsAppTemplateStatusUpdateSchema.safeParse(change.value);
3049
4239
  if (!update.success) {
3050
4240
  await this.params.hooks?.onUnhandledWebhookEvent?.({
3051
4241
  field: change.field,
@@ -3057,7 +4247,7 @@ var ReceiveWebhookUseCase = class {
3057
4247
  await this.params.hooks?.onTemplateStatusUpdate?.(update.data);
3058
4248
  return true;
3059
4249
  }
3060
- const quality = import_meta_whatsapp_contracts13.whatsAppPhoneNumberQualityUpdateSchema.safeParse(change.value);
4250
+ const quality = import_meta_whatsapp_contracts19.whatsAppPhoneNumberQualityUpdateSchema.safeParse(change.value);
3061
4251
  if (!quality.success) {
3062
4252
  await this.params.hooks?.onUnhandledWebhookEvent?.({
3063
4253
  field: change.field,
@@ -3119,6 +4309,7 @@ var ReceiveWebhookUseCase = class {
3119
4309
  });
3120
4310
  if (!updated) return;
3121
4311
  this.params.realtime?.emit(`conv:${updated.whatsappNumber}`, "message-status", {
4312
+ companyId,
3122
4313
  waMessageId: status.id,
3123
4314
  status: status.status
3124
4315
  });
@@ -3188,7 +4379,7 @@ var StorePreviewMediaUseCase = class {
3188
4379
  key
3189
4380
  });
3190
4381
  return {
3191
- mediaId: (0, import_meta_whatsapp_contracts9.toPreviewMediaId)(uploadId),
4382
+ mediaId: (0, import_meta_whatsapp_contracts15.toPreviewMediaId)(uploadId),
3192
4383
  uploadId
3193
4384
  };
3194
4385
  }
@@ -3210,7 +4401,9 @@ function createMetaWhatsAppModule(params) {
3210
4401
  isEnabled: true,
3211
4402
  objectStorage: providers.objectStorage
3212
4403
  } : void 0;
3213
- const channel = new WhatsAppChannelAdapter(messageProvider, previewMediaSupport);
4404
+ const channel = new WhatsAppChannelAdapter(messageProvider, previewMediaSupport, params.features?.previewContacts ? {
4405
+ isEnabled: true
4406
+ } : void 0);
3214
4407
  const sessionRepository = new SessionRepository(db);
3215
4408
  const messageRepository = new MessageRepository(db);
3216
4409
  const settingsRepository = new SettingsRepository(db);
@@ -3221,6 +4414,40 @@ function createMetaWhatsAppModule(params) {
3221
4414
  const flowMediaRepository = new FlowMediaRepository(db);
3222
4415
  const logMessage = new LogMessageUseCase(sessionRepository, messageRepository, providers.realtime, providers.moderator);
3223
4416
  const sendMessage = new SendMessageUseCase(channel, sessionRepository, logMessage, providers.objectStorage, documentRepository);
4417
+ const requestHuman = new RequestHumanConversationUseCase(sessionRepository, providers.realtime, hooks);
4418
+ const flowInterpreter = flowEngineEnabled ? new FlowInterpreter() : void 0;
4419
+ const flowRunnerFeature = params.features?.flowRunner ?? false;
4420
+ const flowRunnerConfig = flowInterpreter && flowRunnerFeature ? flowRunnerFeature === true ? {} : flowRunnerFeature : void 0;
4421
+ const flowHandoff = flowRunnerConfig ? new FlowHandoff({
4422
+ requestHuman,
4423
+ sendMessage,
4424
+ startState,
4425
+ config: flowRunnerConfig.handoff ?? {},
4426
+ now: flowRunnerConfig.now ?? (() => /* @__PURE__ */ new Date()),
4427
+ interpolation: flowRunnerConfig.formatValue ? {
4428
+ formatValue: flowRunnerConfig.formatValue
4429
+ } : {},
4430
+ ...hooks ? {
4431
+ hooks
4432
+ } : {}
4433
+ }) : void 0;
4434
+ const flowRunner = flowInterpreter && flowRunnerConfig && flowHandoff ? new FlowRunner({
4435
+ interpreter: flowInterpreter,
4436
+ flowGraphRepository,
4437
+ sessionRepository,
4438
+ sendMessage,
4439
+ channel,
4440
+ handoff: flowHandoff,
4441
+ lock: providers.flowTurnLock ?? new PostgresAdvisoryFlowTurnLock(db),
4442
+ startState,
4443
+ config: flowRunnerConfig,
4444
+ ...hooks ? {
4445
+ hooks
4446
+ } : {}
4447
+ }) : void 0;
4448
+ if (flowInterpreter && flowRunner && flowHandoff) {
4449
+ flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts20.FLOW_ACTION_KIND.HANDOFF, flowHandoff.createActionHandler((turn) => flowRunner.variablesFor(turn)));
4450
+ }
3224
4451
  const receiveWebhook = new ReceiveWebhookUseCase({
3225
4452
  appSecret: config.appSecret,
3226
4453
  phoneNumberId: config.phoneNumberId,
@@ -3234,11 +4461,13 @@ function createMetaWhatsAppModule(params) {
3234
4461
  ...providers.inboundQueue ? {
3235
4462
  inboundQueue: providers.inboundQueue
3236
4463
  } : {},
3237
- redactInboundLocation: params.features?.redactInboundLocation ?? false
4464
+ redactInboundLocation: params.features?.redactInboundLocation ?? false,
4465
+ ...flowRunner ? {
4466
+ flowRunner
4467
+ } : {}
3238
4468
  });
3239
- const flowInterpreter = flowEngineEnabled ? new FlowInterpreter() : void 0;
3240
4469
  if (flowInterpreter && providers.objectStorage?.getObject) {
3241
- flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts14.FLOW_ACTION_KIND.SEND_MEDIA, createSendMediaAction({
4470
+ flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts20.FLOW_ACTION_KIND.SEND_MEDIA, createSendMediaAction({
3242
4471
  flowMediaRepository,
3243
4472
  objectStorage: providers.objectStorage,
3244
4473
  logMessage,
@@ -3255,7 +4484,7 @@ function createMetaWhatsAppModule(params) {
3255
4484
  }));
3256
4485
  }
3257
4486
  if (flowInterpreter && providers.catalog && config.catalogId) {
3258
- flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts14.FLOW_ACTION_KIND.SEND_PRODUCT_LIST, createSendProductListAction({
4487
+ flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts20.FLOW_ACTION_KIND.SEND_PRODUCT_LIST, createSendProductListAction({
3259
4488
  catalog: providers.catalog,
3260
4489
  catalogId: config.catalogId,
3261
4490
  logMessage,
@@ -3307,7 +4536,7 @@ function createMetaWhatsAppModule(params) {
3307
4536
  takeover: new TakeoverConversationUseCase(sessionRepository, providers.realtime, hooks),
3308
4537
  release: new ReleaseConversationUseCase(sessionRepository, providers.realtime, hooks),
3309
4538
  // Marca o pedido de atendimento (fila "aguardando atendimento") e dispara `onHumanRequested`.
3310
- requestHuman: new RequestHumanConversationUseCase(sessionRepository, providers.realtime, hooks),
4539
+ requestHuman,
3311
4540
  list: new ListConversationsUseCase(sessionRepository),
3312
4541
  listMessages: new ListMessagesUseCase(sessionRepository, messageRepository),
3313
4542
  listDocuments,
@@ -3346,6 +4575,18 @@ function createMetaWhatsAppModule(params) {
3346
4575
  webhook: {
3347
4576
  receive: receiveWebhook,
3348
4577
  // GET de verificação da Meta — o host liga na sua rota e devolve o retorno como texto puro.
4578
+ /**
4579
+ * Comando do simulador (ponte do `conversations-ui`) → payload da Meta com o `phone_number_id`
4580
+ * DESTE módulo. Montar com o padrão do builder fazia o filtro de número descartar a entrega.
4581
+ * Quem assina e entrega em `receive` é a rota do host.
4582
+ */
4583
+ buildPreviewPayload: /* @__PURE__ */ __name((command, envelope) => (0, import_testing.buildPreviewInboundPayload)(command, {
4584
+ ...config.wabaId ? {
4585
+ wabaId: config.wabaId
4586
+ } : {},
4587
+ ...envelope,
4588
+ phoneNumberId: config.phoneNumberId
4589
+ }), "buildPreviewPayload"),
3349
4590
  verifyChallenge: /* @__PURE__ */ __name((query) => verifyWebhookChallenge({
3350
4591
  ...query,
3351
4592
  expectedToken: config.webhookVerifyToken
@@ -3359,6 +4600,9 @@ function createMetaWhatsAppModule(params) {
3359
4600
  } : {},
3360
4601
  ...providers.realtime ? {
3361
4602
  realtime: providers.realtime
4603
+ } : {},
4604
+ ...flowRunner ? {
4605
+ flowRunner
3362
4606
  } : {}
3363
4607
  }), hooks)
3364
4608
  },
@@ -3366,6 +4610,12 @@ function createMetaWhatsAppModule(params) {
3366
4610
  flows: flowInterpreter ? {
3367
4611
  interpreter: flowInterpreter,
3368
4612
  registerFlowAction: /* @__PURE__ */ __name((kind, handler) => flowInterpreter.registerFlowAction(kind, handler), "registerFlowAction"),
4613
+ // undefined quando `features.flowRunner` está desligado — o host dirige a conversa.
4614
+ runner: flowRunner,
4615
+ registerDynamicChoiceProvider: /* @__PURE__ */ __name((key, provider) => {
4616
+ if (!flowRunner) throw new import_meta_whatsapp_contracts20.ConfigMissingError("features.flowRunner");
4617
+ flowRunner.registerDynamicChoiceProvider(key, provider);
4618
+ }, "registerDynamicChoiceProvider"),
3369
4619
  get: new GetFlowGraphUseCase(flowGraphRepository),
3370
4620
  list: new ListFlowGraphsUseCase(flowGraphRepository),
3371
4621
  create: new CreateFlowGraphUseCase(flowGraphRepository),
@@ -3493,18 +4743,26 @@ __name(redeemSseTicket, "redeemSseTicket");
3493
4743
  CreateFlowGraphUseCase,
3494
4744
  DEFAULT_FALLBACK_LIST_LABEL,
3495
4745
  DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
4746
+ DEFAULT_FLOW_TEXT,
4747
+ DEFAULT_MAX_INVALID_ANSWERS,
4748
+ DEFAULT_START_FLOW_KEY,
4749
+ DYNAMIC_CHOICE_MORE_ID,
3496
4750
  DeleteConversationUseCase,
3497
4751
  DeleteFlowGraphUseCase,
3498
4752
  DocumentRepository,
3499
4753
  ExportConversationUseCase,
4754
+ FLOW_RUNTIME_CONTEXT_KEY,
3500
4755
  FlowGraphCache,
3501
4756
  FlowGraphRepository,
4757
+ FlowHandoff,
3502
4758
  FlowInterpreter,
3503
4759
  FlowMediaIdRepository,
3504
4760
  FlowMediaRepository,
4761
+ FlowRunner,
3505
4762
  GetFlowGraphUseCase,
3506
4763
  GetLiveFlowPositionsUseCase,
3507
4764
  INBOUND_LOCATION_CONTENT,
4765
+ InProcessFlowTurnLock,
3508
4766
  InboundEffectsDispatcher,
3509
4767
  IngestInboundMediaUseCase,
3510
4768
  InvalidFlowGraphError,
@@ -3519,6 +4777,7 @@ __name(redeemSseTicket, "redeemSseTicket");
3519
4777
  OptimisticLockError,
3520
4778
  PREVIEW_MEDIA_ID_PREFIX,
3521
4779
  PRODUCT_LIST_LIMIT,
4780
+ PostgresAdvisoryFlowTurnLock,
3522
4781
  ProcessInboundDispatchUseCase,
3523
4782
  PurgeExpiredDocumentsUseCase,
3524
4783
  ReceiveWebhookUseCase,
@@ -3538,6 +4797,7 @@ __name(redeemSseTicket, "redeemSseTicket");
3538
4797
  WEBHOOK_CLAIM_TTL_SECONDS,
3539
4798
  WEBHOOK_NONCE_TTL_SECONDS,
3540
4799
  WhatsAppChannelAdapter,
4800
+ buildFlowChoiceMessage,
3541
4801
  buildInboundJobId,
3542
4802
  claimWebhookDelivery,
3543
4803
  confirmWebhookDelivery,
@@ -3550,14 +4810,19 @@ __name(redeemSseTicket, "redeemSseTicket");
3550
4810
  flowGraphs,
3551
4811
  flowMedia,
3552
4812
  isAudioMimeType,
4813
+ isChoiceNode,
3553
4814
  isRetriableTranscriptionError,
3554
4815
  isUnsupportedTranscriptionError,
3555
4816
  issueSseTicket,
3556
4817
  messages,
3557
4818
  metaWhatsAppMigrationsFolder,
3558
4819
  metaWhatsAppSchema,
4820
+ readFlowInbound,
3559
4821
  redeemSseTicket,
3560
4822
  resolveFailureStatus,
4823
+ resolveFlowAnswer,
4824
+ resolveFlowConfigText,
4825
+ resolveFlowTimeZone,
3561
4826
  resolvePreviewUploadId,
3562
4827
  runMetaWhatsAppMigrations,
3563
4828
  sessions,