@adatechnology/meta-whatsapp-module 0.10.0 → 0.12.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.d.ts CHANGED
@@ -2,12 +2,34 @@ import { PreviewInboundCommand, PreviewPayloadEnvelope } from '@adatechnology/me
2
2
  import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
3
3
  import { PgAsyncDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';
4
4
  import * as _adatechnology_meta_whatsapp_contracts from '@adatechnology/meta-whatsapp-contracts';
5
- import { TranscriptionMode, SessionState, SessionMode, ConversationSummary, MessageDirection, MessageSender, MessageStatus, WhatsAppStatusError, CacheInterface, FlowGraphData, FlowGraphSummary, LiveFlowPosition, WhatsAppSettings, RealtimeNotifierInterface, ChannelAdapterInterface, ObjectStorageInterface, InteractiveMessage, MetaWhatsAppHooks, FlowActionKind, FlowActionHandler, ConversationSession, FlowNodeData, FlowAnswerRejection, FlowDateLocale, BusinessHours, InterpolateFlowTextOptions, DynamicChoiceProvider, WhatsAppMessage, WhatsAppStatus, SubjectResolverInterface, CatalogPort, SendChannelMediaParams, ChannelInteractiveListParams, ChannelInteractiveButtonsParams, FlowClock } from '@adatechnology/meta-whatsapp-contracts';
5
+ import { TranscriptionMode, SessionState, SessionMode, ConversationSummary, MessageDirection, MessageSender, MessageStatus, WhatsAppStatusError, CacheInterface, FlowGraphData, FlowGraphSummary, LiveFlowPosition, WhatsAppSettings, RealtimeNotifierInterface, ChannelAdapterInterface, ObjectStorageInterface, InteractiveMessage, MetaWhatsAppHooks, WhatsAppQuickReplyInput, ListWhatsAppQuickRepliesQuery, WhatsAppQuickReply, FlowActionKind, FlowActionHandler, ConversationSession, FlowNodeData, FlowAnswerRejection, FlowDateLocale, BusinessHours, InterpolateFlowTextOptions, DynamicChoiceProvider, WhatsAppMessage, WhatsAppStatus, SubjectResolverInterface, CatalogPort, SendChannelMediaParams, ChannelInteractiveListParams, ChannelInteractiveButtonsParams, FlowClock } from '@adatechnology/meta-whatsapp-contracts';
6
6
  export { PREVIEW_MEDIA_ID_PREFIX, TranscriptionMode, resolvePreviewUploadId, toPreviewMediaId } from '@adatechnology/meta-whatsapp-contracts';
7
7
  import { WhatsAppMessageProvider } from '@adatechnology/meta-whatsapp-provider';
8
+ import { ModuleRouteTable } from '@adatechnology/module-http';
8
9
  export { WEBHOOK_CLAIM_TTL_SECONDS, WEBHOOK_NONCE_TTL_SECONDS } from '@adatechnology/meta-graph-core';
9
10
 
10
- type MetaWhatsAppDatabase = PgAsyncDatabase<PgQueryResultHKT>;
11
+ type QueryBuilderMethod = (...args: never[]) => unknown;
12
+ /**
13
+ * Forma mínima de uma conexão Drizzle Postgres: os métodos do query builder que o módulo chama.
14
+ * É o que um host em drizzle-orm 0.36–0.45 (`PgDatabase`, sem `PgAsyncDatabase`) é checado contra —
15
+ * um `Pool` do `pg` ou outro objeto qualquer não passa.
16
+ */
17
+ type MetaWhatsAppDatabaseShape = {
18
+ readonly select: QueryBuilderMethod;
19
+ readonly insert: QueryBuilderMethod;
20
+ readonly update: QueryBuilderMethod;
21
+ readonly delete: QueryBuilderMethod;
22
+ readonly execute: QueryBuilderMethod;
23
+ readonly transaction: QueryBuilderMethod;
24
+ };
25
+ type IsAny<TValue> = 0 extends 1 & TValue ? true : false;
26
+ /**
27
+ * `PgAsyncDatabase` só existe no drizzle-orm 1.x. Num host em 0.x o import acima não resolve e, com
28
+ * `skipLibCheck`, vira `any` — qualquer coisa passava como `db`. Nesse caso vale a forma mínima; em
29
+ * 1.x continua o tipo exato, sem mudança para quem já usa.
30
+ */
31
+ type MetaWhatsAppDatabaseFor<TAsyncDatabase> = IsAny<TAsyncDatabase> extends true ? MetaWhatsAppDatabaseShape : TAsyncDatabase;
32
+ type MetaWhatsAppDatabase = MetaWhatsAppDatabaseFor<PgAsyncDatabase<PgQueryResultHKT>>;
11
33
  type DrizzleMigrateFunction = (db: never, config: {
12
34
  migrationsFolder: string;
13
35
  migrationsTable?: string;
@@ -942,6 +964,36 @@ declare const flowGraphs: drizzle_orm_pg_core.PgTableWithColumns<{
942
964
  identity: undefined;
943
965
  generated: undefined;
944
966
  }>;
967
+ origin: drizzle_orm_pg_core.PgBuildColumn<"flow_graphs", drizzle_orm_pg_core.SetHasDefault<drizzle_orm_pg_core.SetNotNull<drizzle_orm_pg_core.PgVarcharBuilder<[string, ...string[]]>>>, {
968
+ name: string;
969
+ tableName: "flow_graphs";
970
+ dataType: "string";
971
+ data: string;
972
+ driverParam: string;
973
+ notNull: true;
974
+ hasDefault: true;
975
+ isPrimaryKey: false;
976
+ isAutoincrement: false;
977
+ hasRuntimeDefault: false;
978
+ enumValues: undefined;
979
+ identity: undefined;
980
+ generated: undefined;
981
+ }>;
982
+ seedVersion: drizzle_orm_pg_core.PgBuildColumn<"flow_graphs", drizzle_orm_pg_core.PgVarcharBuilder<[string, ...string[]]>, {
983
+ name: string;
984
+ tableName: "flow_graphs";
985
+ dataType: "string";
986
+ data: string;
987
+ driverParam: string;
988
+ notNull: false;
989
+ hasDefault: false;
990
+ isPrimaryKey: false;
991
+ isAutoincrement: false;
992
+ hasRuntimeDefault: false;
993
+ enumValues: undefined;
994
+ identity: undefined;
995
+ generated: undefined;
996
+ }>;
945
997
  createdAt: drizzle_orm_pg_core.PgBuildColumn<"flow_graphs", drizzle_orm_pg_core.SetHasDefault<drizzle_orm_pg_core.SetNotNull<drizzle_orm_pg_core.PgTimestampBuilder>>, {
946
998
  name: string;
947
999
  tableName: "flow_graphs";
@@ -1205,6 +1257,139 @@ declare const flowMedia: drizzle_orm_pg_core.PgTableWithColumns<{
1205
1257
  };
1206
1258
  dialect: "pg";
1207
1259
  }>;
1260
+ /**
1261
+ * Respostas rápidas por empresa — o texto pronto que o atendente chama com `/atalho` no composer.
1262
+ *
1263
+ * Só texto: anexos de resposta rápida não existem aqui. O atalho é único por empresa, e a lista
1264
+ * volta inteira (teto em `QUICK_REPLY_LIMITS.MAX_PER_COMPANY`), ordenada por `sortOrder`.
1265
+ */
1266
+ declare const quickReplies: drizzle_orm_pg_core.PgTableWithColumns<{
1267
+ name: "quick_replies";
1268
+ schema: "meta_whatsapp";
1269
+ columns: {
1270
+ id: drizzle_orm_pg_core.PgBuildColumn<"quick_replies", drizzle_orm_pg_core.SetHasDefault<drizzle_orm_pg_core.SetIsPrimaryKey<drizzle_orm_pg_core.PgUUIDBuilder>>, {
1271
+ name: string;
1272
+ tableName: "quick_replies";
1273
+ dataType: "string uuid";
1274
+ data: string;
1275
+ driverParam: string;
1276
+ notNull: true;
1277
+ hasDefault: true;
1278
+ isPrimaryKey: false;
1279
+ isAutoincrement: false;
1280
+ hasRuntimeDefault: false;
1281
+ enumValues: undefined;
1282
+ identity: undefined;
1283
+ generated: undefined;
1284
+ }>;
1285
+ companyId: drizzle_orm_pg_core.PgBuildColumn<"quick_replies", drizzle_orm_pg_core.SetNotNull<drizzle_orm_pg_core.PgUUIDBuilder>, {
1286
+ name: string;
1287
+ tableName: "quick_replies";
1288
+ dataType: "string uuid";
1289
+ data: string;
1290
+ driverParam: string;
1291
+ notNull: true;
1292
+ hasDefault: false;
1293
+ isPrimaryKey: false;
1294
+ isAutoincrement: false;
1295
+ hasRuntimeDefault: false;
1296
+ enumValues: undefined;
1297
+ identity: undefined;
1298
+ generated: undefined;
1299
+ }>;
1300
+ title: drizzle_orm_pg_core.PgBuildColumn<"quick_replies", drizzle_orm_pg_core.SetNotNull<drizzle_orm_pg_core.PgVarcharBuilder<[string, ...string[]]>>, {
1301
+ name: string;
1302
+ tableName: "quick_replies";
1303
+ dataType: "string";
1304
+ data: string;
1305
+ driverParam: string;
1306
+ notNull: true;
1307
+ hasDefault: false;
1308
+ isPrimaryKey: false;
1309
+ isAutoincrement: false;
1310
+ hasRuntimeDefault: false;
1311
+ enumValues: undefined;
1312
+ identity: undefined;
1313
+ generated: undefined;
1314
+ }>;
1315
+ shortcut: drizzle_orm_pg_core.PgBuildColumn<"quick_replies", drizzle_orm_pg_core.SetNotNull<drizzle_orm_pg_core.PgVarcharBuilder<[string, ...string[]]>>, {
1316
+ name: string;
1317
+ tableName: "quick_replies";
1318
+ dataType: "string";
1319
+ data: string;
1320
+ driverParam: string;
1321
+ notNull: true;
1322
+ hasDefault: false;
1323
+ isPrimaryKey: false;
1324
+ isAutoincrement: false;
1325
+ hasRuntimeDefault: false;
1326
+ enumValues: undefined;
1327
+ identity: undefined;
1328
+ generated: undefined;
1329
+ }>;
1330
+ body: drizzle_orm_pg_core.PgBuildColumn<"quick_replies", drizzle_orm_pg_core.SetNotNull<drizzle_orm_pg_core.PgVarcharBuilder<[string, ...string[]]>>, {
1331
+ name: string;
1332
+ tableName: "quick_replies";
1333
+ dataType: "string";
1334
+ data: string;
1335
+ driverParam: string;
1336
+ notNull: true;
1337
+ hasDefault: false;
1338
+ isPrimaryKey: false;
1339
+ isAutoincrement: false;
1340
+ hasRuntimeDefault: false;
1341
+ enumValues: undefined;
1342
+ identity: undefined;
1343
+ generated: undefined;
1344
+ }>;
1345
+ sortOrder: drizzle_orm_pg_core.PgBuildColumn<"quick_replies", drizzle_orm_pg_core.SetHasDefault<drizzle_orm_pg_core.SetNotNull<drizzle_orm_pg_core.PgIntegerBuilder>>, {
1346
+ name: string;
1347
+ tableName: "quick_replies";
1348
+ dataType: "number int32";
1349
+ data: number;
1350
+ driverParam: string | number;
1351
+ notNull: true;
1352
+ hasDefault: true;
1353
+ isPrimaryKey: false;
1354
+ isAutoincrement: false;
1355
+ hasRuntimeDefault: false;
1356
+ enumValues: undefined;
1357
+ identity: undefined;
1358
+ generated: undefined;
1359
+ }>;
1360
+ createdAt: drizzle_orm_pg_core.PgBuildColumn<"quick_replies", drizzle_orm_pg_core.SetHasDefault<drizzle_orm_pg_core.SetNotNull<drizzle_orm_pg_core.PgTimestampBuilder>>, {
1361
+ name: string;
1362
+ tableName: "quick_replies";
1363
+ dataType: "object date";
1364
+ data: Date;
1365
+ driverParam: string;
1366
+ notNull: true;
1367
+ hasDefault: true;
1368
+ isPrimaryKey: false;
1369
+ isAutoincrement: false;
1370
+ hasRuntimeDefault: false;
1371
+ enumValues: undefined;
1372
+ identity: undefined;
1373
+ generated: undefined;
1374
+ }>;
1375
+ updatedAt: drizzle_orm_pg_core.PgBuildColumn<"quick_replies", drizzle_orm_pg_core.SetHasDefault<drizzle_orm_pg_core.SetNotNull<drizzle_orm_pg_core.PgTimestampBuilder>>, {
1376
+ name: string;
1377
+ tableName: "quick_replies";
1378
+ dataType: "object date";
1379
+ data: Date;
1380
+ driverParam: string;
1381
+ notNull: true;
1382
+ hasDefault: true;
1383
+ isPrimaryKey: false;
1384
+ isAutoincrement: false;
1385
+ hasRuntimeDefault: false;
1386
+ enumValues: undefined;
1387
+ identity: undefined;
1388
+ generated: undefined;
1389
+ }>;
1390
+ };
1391
+ dialect: "pg";
1392
+ }>;
1208
1393
  declare const settings: drizzle_orm_pg_core.PgTableWithColumns<{
1209
1394
  name: "settings";
1210
1395
  schema: "meta_whatsapp";
@@ -1374,6 +1559,8 @@ type DocumentRow = typeof documents.$inferSelect;
1374
1559
  type NewDocumentRow = typeof documents.$inferInsert;
1375
1560
  type FlowMediaRow = typeof flowMedia.$inferSelect;
1376
1561
  type NewFlowMediaRow = typeof flowMedia.$inferInsert;
1562
+ type QuickReplyRow = typeof quickReplies.$inferSelect;
1563
+ type NewQuickReplyRow = typeof quickReplies.$inferInsert;
1377
1564
 
1378
1565
  interface ListConversationsFilters {
1379
1566
  page?: number;
@@ -1611,6 +1798,22 @@ declare class InvalidFlowGraphError extends Error {
1611
1798
  readonly validationMessage: string;
1612
1799
  constructor(key: string, validationMessage: string);
1613
1800
  }
1801
+ type ReseedFlowGraphParams = {
1802
+ readonly companyId: string;
1803
+ readonly key: string;
1804
+ readonly seedVersion: string;
1805
+ readonly content: Pick<FlowGraphData, 'label' | 'startNodeId' | 'nodes'>;
1806
+ };
1807
+ /**
1808
+ * `updated`: o grafo era seed de outra versão e foi substituído. `current`: já está nessa versão do seed.
1809
+ * `edited`: alguém mexeu pelo editor (ou o grafo é anterior ao campo) — intocado. `missing`: não existe.
1810
+ */
1811
+ type ReseedFlowGraphResult = {
1812
+ readonly status: 'updated';
1813
+ readonly graph: FlowGraphData;
1814
+ } | {
1815
+ readonly status: 'current' | 'edited' | 'missing';
1816
+ };
1614
1817
  declare class OptimisticLockError extends Error {
1615
1818
  constructor(key: string);
1616
1819
  }
@@ -1621,11 +1824,17 @@ declare class FlowGraphRepository {
1621
1824
  get(companyId: string, key: string): Promise<FlowGraphData | undefined>;
1622
1825
  list(companyId: string): Promise<FlowGraphSummary[]>;
1623
1826
  private assertValidNodes;
1624
- create(companyId: string, graph: Omit<FlowGraphData, 'version'> & {
1827
+ create(companyId: string, graph: Omit<FlowGraphData, 'version' | 'origin'> & {
1625
1828
  showInMenu?: boolean;
1626
1829
  menuOptionLabel?: string;
1627
1830
  }): Promise<FlowGraphData>;
1628
1831
  save(companyId: string, graph: FlowGraphData, expectedVersion: number): Promise<FlowGraphData>;
1832
+ /**
1833
+ * Atualiza um grafo semeado que ninguém editou. A condição `origin = 'seed'` vai no próprio UPDATE:
1834
+ * se uma pessoa salvar pelo editor entre a leitura e a escrita, o grafo vira `edited` e este update
1835
+ * não casa nenhuma linha — a edição nunca é sobrescrita. Idempotente por `seedVersion`.
1836
+ */
1837
+ reseed(params: ReseedFlowGraphParams): Promise<ReseedFlowGraphResult>;
1629
1838
  delete(companyId: string, key: string): Promise<void>;
1630
1839
  getLiveFlowPositions(companyId: string): Promise<LiveFlowPosition[]>;
1631
1840
  }
@@ -2076,6 +2285,62 @@ declare class RedactInboundLocationsUseCase {
2076
2285
  execute(params: RedactInboundLocationsParams): Promise<RedactInboundLocationsResult>;
2077
2286
  }
2078
2287
 
2288
+ type ListQuickRepliesParams$1 = {
2289
+ companyId: string;
2290
+ search?: string;
2291
+ };
2292
+ type CreateQuickReplyParams = WhatsAppQuickReplyInput & {
2293
+ companyId: string;
2294
+ };
2295
+ type UpdateQuickReplyParams$1 = WhatsAppQuickReplyInput & {
2296
+ companyId: string;
2297
+ id: string;
2298
+ };
2299
+ declare class QuickReplyRepository {
2300
+ private readonly db;
2301
+ constructor(db: MetaWhatsAppDatabase);
2302
+ list(params: ListQuickRepliesParams$1): Promise<QuickReplyRow[]>;
2303
+ get(companyId: string, id: string): Promise<QuickReplyRow | undefined>;
2304
+ create(params: CreateQuickReplyParams): Promise<QuickReplyRow>;
2305
+ update(params: UpdateQuickReplyParams$1): Promise<QuickReplyRow>;
2306
+ delete(companyId: string, id: string): Promise<boolean>;
2307
+ }
2308
+
2309
+ declare function toQuickReplyView(row: QuickReplyRow): WhatsAppQuickReply;
2310
+ type ListQuickRepliesParams = ListWhatsAppQuickRepliesQuery & {
2311
+ companyId: string;
2312
+ };
2313
+ type SaveQuickReplyParams = WhatsAppQuickReplyInput & {
2314
+ companyId: string;
2315
+ };
2316
+ type UpdateQuickReplyParams = SaveQuickReplyParams & {
2317
+ id: string;
2318
+ };
2319
+ type DeleteQuickReplyParams = {
2320
+ companyId: string;
2321
+ id: string;
2322
+ };
2323
+ declare class ListQuickRepliesUseCase {
2324
+ private readonly repository;
2325
+ constructor(repository: QuickReplyRepository);
2326
+ execute(params: ListQuickRepliesParams): Promise<WhatsAppQuickReply[]>;
2327
+ }
2328
+ declare class CreateQuickReplyUseCase {
2329
+ private readonly repository;
2330
+ constructor(repository: QuickReplyRepository);
2331
+ execute(params: SaveQuickReplyParams): Promise<WhatsAppQuickReply>;
2332
+ }
2333
+ declare class UpdateQuickReplyUseCase {
2334
+ private readonly repository;
2335
+ constructor(repository: QuickReplyRepository);
2336
+ execute(params: UpdateQuickReplyParams): Promise<WhatsAppQuickReply>;
2337
+ }
2338
+ declare class DeleteQuickReplyUseCase {
2339
+ private readonly repository;
2340
+ constructor(repository: QuickReplyRepository);
2341
+ execute(params: DeleteQuickReplyParams): Promise<void>;
2342
+ }
2343
+
2079
2344
  type ExportConversationParams = {
2080
2345
  companyId: string;
2081
2346
  whatsappNumber: string;
@@ -2113,6 +2378,8 @@ type CreateFlowGraphParams = {
2113
2378
  nodes: FlowGraphData['nodes'];
2114
2379
  showInMenu?: boolean;
2115
2380
  menuOptionLabel?: string;
2381
+ /** Só o produto semeando informa: marca o grafo como `seed` dessa versão (ver `ReseedFlowGraphUseCase`). */
2382
+ seedVersion?: string;
2116
2383
  };
2117
2384
  declare class CreateFlowGraphUseCase {
2118
2385
  private readonly flowGraphRepository;
@@ -2129,6 +2396,15 @@ declare class SaveFlowGraphUseCase {
2129
2396
  constructor(flowGraphRepository: FlowGraphRepository);
2130
2397
  execute(params: SaveFlowGraphParams): Promise<FlowGraphData>;
2131
2398
  }
2399
+ /**
2400
+ * Atualiza grafos semeados que o dono nunca editou quando o seed do produto muda, sem apagar à mão.
2401
+ * Grafo editado pelo painel (ou anterior ao campo `origin`) nunca é tocado.
2402
+ */
2403
+ declare class ReseedFlowGraphUseCase {
2404
+ private readonly flowGraphRepository;
2405
+ constructor(flowGraphRepository: FlowGraphRepository);
2406
+ execute(params: ReseedFlowGraphParams): Promise<ReseedFlowGraphResult>;
2407
+ }
2132
2408
  declare class DeleteFlowGraphUseCase {
2133
2409
  private readonly flowGraphRepository;
2134
2410
  constructor(flowGraphRepository: FlowGraphRepository);
@@ -2217,18 +2493,67 @@ declare class FlowInterpreter {
2217
2493
  * os textos padrão em pt-BR e encaminhamento a uma pessoa depois de 2 respostas inválidas.
2218
2494
  */
2219
2495
 
2496
+ /** Qual texto do runner está sendo pedido ao resolvedor. */
2497
+ type FlowTextKind = 'fallback' | 'rejection' | 'non-text-answer' | 'handoff' | 'handoff-out-of-hours';
2498
+ type FlowTextContext = {
2499
+ readonly companyId: string;
2500
+ readonly whatsappNumber: string;
2501
+ readonly kind: FlowTextKind;
2502
+ /** Só em `kind: 'rejection'`. */
2503
+ readonly rejection?: FlowAnswerRejection;
2504
+ /** Nó em que a conversa está, quando há um. */
2505
+ readonly nodeId?: string;
2506
+ readonly flowKey?: string | null;
2507
+ };
2508
+ /**
2509
+ * Texto resolvido a cada uso, por empresa/conversa (modelos editados no painel, idioma do cliente).
2510
+ * `undefined` cai no próximo texto da cadeia e, no fim, no padrão do pacote. O texto devolvido aceita
2511
+ * `{{chave}}` como o fixo. Se lançar, o erro vai para `onFlowRunnerError` (`stage: 'text'`) e vale o
2512
+ * padrão — o cliente nunca fica sem resposta por causa do resolvedor.
2513
+ */
2514
+ type FlowTextResolver = (context: FlowTextContext) => string | undefined | Promise<string | undefined>;
2515
+ /** Texto fixo ou resolvido por empresa/conversa. */
2516
+ type FlowConfigText = string | FlowTextResolver;
2517
+ /** O que o validador do host devolve: `undefined`/`{ isValid: true }` aceita. */
2518
+ type FlowAnswerValidatorResult = undefined | {
2519
+ readonly isValid: true;
2520
+ }
2521
+ /** `message` (aceita `{{chave}}`) substitui o texto de nova tentativa só desta vez. */
2522
+ | {
2523
+ readonly isValid: false;
2524
+ readonly message?: string;
2525
+ };
2526
+ /**
2527
+ * Validação extra do host, depois da do pacote ter aceitado a resposta (formato, mínimo, máximo).
2528
+ * Ex.: horário dentro das faixas livres da agenda, data com vaga. Recusa conta como resposta inválida
2529
+ * (`rejected-by-host`), com o mesmo mecanismo de nova tentativa e encaminhamento.
2530
+ */
2531
+ type FlowAnswerValidator = (params: {
2532
+ readonly companyId: string;
2533
+ readonly session: ConversationSession;
2534
+ readonly node: FlowNodeData;
2535
+ /** Texto do cliente, aparado. */
2536
+ readonly answer: string;
2537
+ /** Valor já convertido pelo pacote (`HH:MM`, `yyyy-mm-dd`, número...). */
2538
+ readonly value: unknown;
2539
+ readonly context: Readonly<Record<string, unknown>>;
2540
+ }) => FlowAnswerValidatorResult | Promise<FlowAnswerValidatorResult>;
2220
2541
  /** `restart` volta ao início do fluxo de partida; `handoff` chama uma pessoa; `flow:<chave>` abre outro fluxo. */
2221
2542
  type FlowGlobalKeywordTarget = 'restart' | 'handoff' | `flow:${string}`;
2543
+ /** `exact`: a mensagem inteira é a palavra; `word`: a palavra aparece inteira dentro da mensagem. */
2544
+ type FlowGlobalKeywordMatch = 'exact' | 'word';
2222
2545
  /** Palavras que valem em qualquer nó ("menu", "atendente"), comparadas sem acento e sem caixa. */
2223
2546
  type FlowGlobalKeyword = {
2224
2547
  readonly keywords: readonly string[];
2548
+ /** Padrão `exact`. Com `word`, "quero falar com o atendente" aciona "atendente"; a palavra mais longa vence. */
2549
+ readonly match?: FlowGlobalKeywordMatch;
2225
2550
  readonly target: FlowGlobalKeywordTarget;
2226
2551
  };
2227
2552
  type FlowHandoffConfig = {
2228
2553
  /** Mensagem dentro do horário (ou sempre, sem `businessHours`). Aceita `{{chave}}`. */
2229
- readonly message?: string;
2554
+ readonly message?: FlowConfigText;
2230
2555
  /** Mensagem fora do horário. Ausente, vale `message`. */
2231
- readonly outOfHoursMessage?: string;
2556
+ readonly outOfHoursMessage?: FlowConfigText;
2232
2557
  /** Fixo, ou resolvido por empresa a cada encaminhamento (o painel pode mudar sem deploy). */
2233
2558
  readonly businessHours?: BusinessHours | ((companyId: string) => Promise<BusinessHours | undefined>);
2234
2559
  };
@@ -2243,11 +2568,12 @@ type FlowRunnerConfig = {
2243
2568
  /** Respostas inválidas seguidas no mesmo nó antes de chamar uma pessoa. Padrão 2; o nó pode sobrescrever. */
2244
2569
  readonly maxInvalidAnswers?: number;
2245
2570
  /** Texto de nova tentativa quando o nó não declara `fallbackMessage`. */
2246
- readonly defaultFallbackMessage?: string;
2571
+ readonly defaultFallbackMessage?: FlowConfigText;
2247
2572
  /** Texto de nova tentativa por motivo, antes do padrão ("essa data já passou"). */
2248
- readonly rejectionMessages?: Partial<Record<FlowAnswerRejection, string>>;
2573
+ readonly rejectionMessages?: Partial<Record<FlowAnswerRejection, FlowConfigText>>;
2249
2574
  /** Corpo de escolha quando o nó não tem `question` (a Meta exige corpo). */
2250
2575
  readonly choicePrompt?: string;
2576
+ /** Texto do botão que abre a lista; aceita `{{chave}}`, como o título das opções. Acima de 20 caracteres a escolha sai numerada. */
2251
2577
  readonly listButtonLabel?: string;
2252
2578
  /** Rótulo da linha que pede a próxima página de um `dynamic_choice`. */
2253
2579
  readonly seeMoreLabel?: string;
@@ -2261,7 +2587,9 @@ type FlowRunnerConfig = {
2261
2587
  /** Resposta que não casa com opção: `reask` (padrão) ou `default` (segue `next.default`). O nó sobrescreve. */
2262
2588
  readonly unmatchedChoice?: 'reask' | 'default';
2263
2589
  /** Resposta em áudio, imagem, localização… num nó que espera texto: avisa e repergunta, sem contar tentativa. */
2264
- readonly nonTextAnswerMessage?: string;
2590
+ readonly nonTextAnswerMessage?: FlowConfigText;
2591
+ /** Validação extra das perguntas (não de escolha), depois da do pacote. Ver `FlowAnswerValidator`. */
2592
+ readonly validateAnswer?: FlowAnswerValidator;
2265
2593
  readonly handoff?: FlowHandoffConfig;
2266
2594
  /**
2267
2595
  * Conversa que pediu atendimento e saiu do fluxo: `silent` (padrão) não responde até alguém
@@ -2433,8 +2761,17 @@ declare class FlowRunner {
2433
2761
  */
2434
2762
  private applyGlobalTarget;
2435
2763
  private answerNode;
2764
+ /** Títulos como o cliente os viu (`{{chave}}` resolvido): é contra eles que o texto digitado casa. */
2765
+ private renderedOptions;
2766
+ /**
2767
+ * Validador do host, só para pergunta (escolha já casou com opção) e nunca para resposta pulada.
2768
+ * Falha do validador não pode prender o cliente na pergunta: reporta e aceita.
2769
+ */
2770
+ private validateWithHost;
2771
+ private configText;
2436
2772
  private followsDefaultWhenUnmatched;
2437
2773
  private handleInvalid;
2774
+ /** Precedência: texto do validador do host, `fallbackMessage` do nó, texto do motivo, padrão do host, do pacote. */
2438
2775
  private fallbackText;
2439
2776
  private handOff;
2440
2777
  private jumpTo;
@@ -3044,6 +3381,18 @@ declare function createMetaWhatsAppModule(params: CreateMetaWhatsAppModuleParams
3044
3381
  resolvePolicy: (companyId: string) => Promise<TranscriptionPolicy>;
3045
3382
  } | undefined;
3046
3383
  settings: SettingsRepository;
3384
+ /**
3385
+ * Respostas rápidas por empresa (o `/atalho` do composer). Só texto. As rotas HTTP saem de
3386
+ * `createMetaWhatsAppQuickReplyRoutes({ module })`; o host que prefere as próprias usa os
3387
+ * casos de uso daqui.
3388
+ */
3389
+ quickReplies: {
3390
+ list: ListQuickRepliesUseCase;
3391
+ create: CreateQuickReplyUseCase;
3392
+ update: UpdateQuickReplyUseCase;
3393
+ delete: DeleteQuickReplyUseCase;
3394
+ repository: QuickReplyRepository;
3395
+ };
3047
3396
  /**
3048
3397
  * `undefined` quando o recurso não está ligado (ou falta storage legível). O host consulta a
3049
3398
  * ausência para não registrar a rota de upload — e o preview, sem a rota, esconde o microfone.
@@ -3201,6 +3550,7 @@ declare function createMetaWhatsAppModule(params: CreateMetaWhatsAppModuleParams
3201
3550
  list: ListFlowGraphsUseCase;
3202
3551
  create: CreateFlowGraphUseCase;
3203
3552
  save: SaveFlowGraphUseCase;
3553
+ reseed: ReseedFlowGraphUseCase;
3204
3554
  delete: DeleteFlowGraphUseCase;
3205
3555
  livePositions: GetLiveFlowPositionsUseCase;
3206
3556
  repository: FlowGraphRepository;
@@ -3365,6 +3715,22 @@ type FlowInbound = {
3365
3715
  };
3366
3716
  declare function readFlowInbound(message: WhatsAppMessage): FlowInbound;
3367
3717
 
3718
+ /**
3719
+ * Copyright (c) 2026 Ada Technology. MIT License.
3720
+ *
3721
+ * Primeiro texto definido de uma cadeia de `FlowConfigText` (fixo ou resolvido por empresa). A cadeia
3722
+ * é a precedência que o runner já tinha — nó, motivo, padrão do host, padrão do pacote —; resolvedor
3723
+ * que devolve `undefined` passa a vez ao próximo.
3724
+ */
3725
+
3726
+ type ResolveFlowConfigTextParams = {
3727
+ readonly chain: readonly (FlowConfigText | undefined)[];
3728
+ readonly context: FlowTextContext;
3729
+ /** Resolvedor que lançou: reporta e segue a cadeia (o padrão do pacote sempre fecha a resposta). */
3730
+ readonly onError?: (error: unknown) => Promise<void> | void;
3731
+ };
3732
+ declare function resolveFlowConfigText(params: ResolveFlowConfigTextParams): Promise<string | undefined>;
3733
+
3368
3734
  /**
3369
3735
  * Copyright (c) 2026 Ada Technology. MIT License.
3370
3736
  *
@@ -3449,6 +3815,11 @@ type ResolveFlowAnswerParams = {
3449
3815
  readonly isInteractiveReply: boolean;
3450
3816
  readonly context: Readonly<Record<string, unknown>>;
3451
3817
  readonly clock: FlowClock;
3818
+ /**
3819
+ * Opções do nó de escolha como o cliente as viu (`{{chave}}` já resolvido). Ausente, `node.options`
3820
+ * cru — o texto digitado casaria com o título ainda com a marcação.
3821
+ */
3822
+ readonly options?: readonly (readonly [string, string])[];
3452
3823
  /** Opções exibidas na última página de um `dynamic_choice` (id, título), incluindo "ver mais". */
3453
3824
  readonly dynamicOptions?: readonly (readonly [string, string])[];
3454
3825
  };
@@ -3583,4 +3954,35 @@ declare class FlowMediaIdRepository implements FlowMediaIdStore {
3583
3954
  }): Promise<void>;
3584
3955
  }
3585
3956
 
3586
- export { type AttachFlowMediaParams, type AudioTranscriber, type BuildFlowChoiceMessageParams, type CompanyDocumentView, type CompanyDocumentsPage, type ConversationDocumentView, type ConversationDocumentsPage, type CountInboundLocationsParams, type CountInboundLocationsResult, CountInboundLocationsUseCase, type CreateFlowGraphParams, CreateFlowGraphUseCase, type CreateMetaWhatsAppModuleParams, type CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FALLBACK_LIST_LABEL, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, DEFAULT_FLOW_TEXT, DEFAULT_MAX_INVALID_ANSWERS, DEFAULT_START_FLOW_KEY, DYNAMIC_CHOICE_MORE_ID, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FLOW_RUNTIME_CONTEXT_KEY, type FlowAnswerDecision, type FlowChoiceOption, type FlowGlobalKeyword, type FlowGlobalKeywordTarget, FlowGraphCache, FlowGraphRepository, type FlowGraphRow, FlowHandoff, type FlowHandoffConfig, type FlowHandoffDependencies, type FlowInbound, FlowInterpreter, type FlowMediaIdCache, FlowMediaIdRepository, type FlowMediaIdStore, type FlowMediaLocation, FlowMediaRepository, type FlowMediaRow, type FlowMediaTranscriptLogger, type FlowOutboundMessage, type FlowRunOptions, type FlowRunResult, FlowRunner, type FlowRunnerConfig, type FlowRunnerDependencies, type FlowRunnerOutcome, type FlowStepInput, type FlowStepResult, type FlowTurnLockInterface, type FlowTurnLockKey, type FlowVariablesResolver, GetFlowGraphUseCase, GetLiveFlowPositionsUseCase, type HandleFlowMessageParams, INBOUND_LOCATION_CONTENT, InProcessFlowTurnLock, type InboundDispatchJob, type InboundDispatchQueueInterface, InboundEffectsDispatcher, type InboundMediaDescriptor, type InboundMessageEffectsJob, type InboundStatusEffectsJob, type IngestInboundMediaParams, type IngestInboundMediaResult, IngestInboundMediaUseCase, type IngestTranscriptionOptions, type InsertMessageParams, InvalidFlowGraphError, type LinkDocumentParams, type ListCompanyDocumentsParams, ListCompanyDocumentsUseCase, type ListConversationDocumentsParams, ListConversationDocumentsUseCase, type ListConversationsFilters, type ListConversationsParams, ListConversationsUseCase, type ListDocumentsParams, type ListDocumentsResult, ListFlowGraphsUseCase, type ListMessagesParams, ListMessagesUseCase, type LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppMigrationsFolderParams, type MetaWhatsAppMigrationsLayout, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, PostgresAdvisoryFlowTurnLock, type PreviewContactsSupport, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, type RealtimeRelay, type ReceiveWebhookParams, type ReceiveWebhookResult, ReceiveWebhookUseCase, type RedactInboundLocationsParams, type RedactInboundLocationsResult, RedactInboundLocationsUseCase, type ReleaseConversationParams, ReleaseConversationUseCase, type ListMessagesParams$1 as RepositoryListMessagesParams, type RequestFlowHandoffParams, type RequestHumanConversationParams, RequestHumanConversationUseCase, type ResolveFlowAnswerParams, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, type SaveTranscriptionByWaMessageIdParams, type SaveTranscriptionParams, type SendInteractiveParams, type SendMediaParams, SendMessageUseCase, type SendTemplateParams, type SendTextParams, SessionRepository, type SessionRow, SettingsRepository, type SettingsRow, SseHub, type SseListener, type StartFlowParams, type StorePreviewMediaParams, type StorePreviewMediaResult, StorePreviewMediaUseCase, TRANSCRIPTION_MODE, TRANSCRIPTION_STATUS, type TakeoverConversationParams, TakeoverConversationUseCase, type TicketStoreInterface, type TranscribeAudioDependencies, type TranscribeAudioParams, type TranscribeAudioResult, TranscribeAudioUseCase, type TranscriptionPolicy, type TranscriptionPolicyDefaults, type TranscriptionPolicyResolver, type TranscriptionStatus, type UpdateFlowMediaParams, WhatsAppChannelAdapter, buildFlowChoiceMessage, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isChoiceNode, isRetriableTranscriptionError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, readFlowInbound, redeemSseTicket, resolveFailureStatus, resolveFlowAnswer, resolveFlowTimeZone, runMetaWhatsAppMigrations, sessions, settings, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
3957
+ /**
3958
+ * Escopo padrão da escrita de respostas rápidas (criar, editar, apagar). A leitura é de qualquer
3959
+ * agente autenticado — o seletor do composer precisa dela —, então não tem escopo padrão. O host
3960
+ * troca o vocabulário em `createMetaWhatsAppQuickReplyRoutes({ scopes })` se o dele for outro.
3961
+ */
3962
+ declare const QUICK_REPLY_SCOPE: {
3963
+ readonly WRITE: "quick-replies:write";
3964
+ };
3965
+ type QuickReplyRouteScopes = {
3966
+ /** Escopos que liberam criar, editar e apagar. Basta um. Padrão: `quick-replies:write`. */
3967
+ readonly write?: readonly string[];
3968
+ /** Exige escopo também na leitura. Ausente, basta estar autenticado como agente. */
3969
+ readonly read?: readonly string[];
3970
+ };
3971
+ declare const DEFAULT_QUICK_REPLY_WRITE_SCOPES: readonly string[];
3972
+
3973
+ type CreateMetaWhatsAppQuickReplyRoutesParams = {
3974
+ readonly module: Pick<MetaWhatsAppModule, 'quickReplies'>;
3975
+ readonly scopes?: QuickReplyRouteScopes;
3976
+ };
3977
+ /**
3978
+ * Tabela de rotas de respostas rápidas (`module-http`). O host escolhe o adaptador (`fetch` ou
3979
+ * uWebSockets) e o prefixo; o `companyId` vem sempre da identidade, nunca do corpo.
3980
+ *
3981
+ * - `GET /quick-replies` agente autenticado; `?search=` filtra título, atalho e texto
3982
+ * - `POST /quick-replies` escopo de escrita; `201`
3983
+ * - `PUT /quick-replies/:id` escopo de escrita; troca título, atalho e texto
3984
+ * - `DELETE /quick-replies/:id` escopo de escrita; `204`
3985
+ */
3986
+ declare function createMetaWhatsAppQuickReplyRoutes(params: CreateMetaWhatsAppQuickReplyRoutesParams): ModuleRouteTable;
3987
+
3988
+ export { type AttachFlowMediaParams, type AudioTranscriber, type BuildFlowChoiceMessageParams, type CompanyDocumentView, type CompanyDocumentsPage, type ConversationDocumentView, type ConversationDocumentsPage, type CountInboundLocationsParams, type CountInboundLocationsResult, CountInboundLocationsUseCase, type CreateFlowGraphParams, CreateFlowGraphUseCase, type CreateMetaWhatsAppModuleParams, type CreateMetaWhatsAppQuickReplyRoutesParams, type CreateQuickReplyParams as CreateQuickReplyRowParams, CreateQuickReplyUseCase, type CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FALLBACK_LIST_LABEL, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, DEFAULT_FLOW_TEXT, DEFAULT_MAX_INVALID_ANSWERS, DEFAULT_QUICK_REPLY_WRITE_SCOPES, DEFAULT_START_FLOW_KEY, DYNAMIC_CHOICE_MORE_ID, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, type DeleteQuickReplyParams, DeleteQuickReplyUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FLOW_RUNTIME_CONTEXT_KEY, type FlowAnswerDecision, type FlowAnswerValidator, type FlowAnswerValidatorResult, type FlowChoiceOption, type FlowConfigText, type FlowGlobalKeyword, type FlowGlobalKeywordMatch, type FlowGlobalKeywordTarget, FlowGraphCache, FlowGraphRepository, type FlowGraphRow, FlowHandoff, type FlowHandoffConfig, type FlowHandoffDependencies, type FlowInbound, FlowInterpreter, type FlowMediaIdCache, FlowMediaIdRepository, type FlowMediaIdStore, type FlowMediaLocation, FlowMediaRepository, type FlowMediaRow, type FlowMediaTranscriptLogger, type FlowOutboundMessage, type FlowRunOptions, type FlowRunResult, FlowRunner, type FlowRunnerConfig, type FlowRunnerDependencies, type FlowRunnerOutcome, type FlowStepInput, type FlowStepResult, type FlowTextContext, type FlowTextKind, type FlowTextResolver, type FlowTurnLockInterface, type FlowTurnLockKey, type FlowVariablesResolver, GetFlowGraphUseCase, GetLiveFlowPositionsUseCase, type HandleFlowMessageParams, INBOUND_LOCATION_CONTENT, InProcessFlowTurnLock, type InboundDispatchJob, type InboundDispatchQueueInterface, InboundEffectsDispatcher, type InboundMediaDescriptor, type InboundMessageEffectsJob, type InboundStatusEffectsJob, type IngestInboundMediaParams, type IngestInboundMediaResult, IngestInboundMediaUseCase, type IngestTranscriptionOptions, type InsertMessageParams, InvalidFlowGraphError, type LinkDocumentParams, type ListCompanyDocumentsParams, ListCompanyDocumentsUseCase, type ListConversationDocumentsParams, ListConversationDocumentsUseCase, type ListConversationsFilters, type ListConversationsParams, ListConversationsUseCase, type ListDocumentsParams, type ListDocumentsResult, ListFlowGraphsUseCase, type ListMessagesParams, ListMessagesUseCase, type ListQuickRepliesParams, ListQuickRepliesUseCase, type ListQuickRepliesParams$1 as ListQuickReplyRowsParams, type LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppDatabaseFor, type MetaWhatsAppDatabaseShape, type MetaWhatsAppMigrationsFolderParams, type MetaWhatsAppMigrationsLayout, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewQuickReplyRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, PostgresAdvisoryFlowTurnLock, type PreviewContactsSupport, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, QUICK_REPLY_SCOPE, QuickReplyRepository, type QuickReplyRouteScopes, type QuickReplyRow, type RealtimeRelay, type ReceiveWebhookParams, type ReceiveWebhookResult, ReceiveWebhookUseCase, type RedactInboundLocationsParams, type RedactInboundLocationsResult, RedactInboundLocationsUseCase, type ReleaseConversationParams, ReleaseConversationUseCase, type ListMessagesParams$1 as RepositoryListMessagesParams, type RequestFlowHandoffParams, type RequestHumanConversationParams, RequestHumanConversationUseCase, type ReseedFlowGraphParams, type ReseedFlowGraphResult, ReseedFlowGraphUseCase, type ResolveFlowAnswerParams, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, type SaveQuickReplyParams, type SaveTranscriptionByWaMessageIdParams, type SaveTranscriptionParams, type SendInteractiveParams, type SendMediaParams, SendMessageUseCase, type SendTemplateParams, type SendTextParams, SessionRepository, type SessionRow, SettingsRepository, type SettingsRow, SseHub, type SseListener, type StartFlowParams, type StorePreviewMediaParams, type StorePreviewMediaResult, StorePreviewMediaUseCase, TRANSCRIPTION_MODE, TRANSCRIPTION_STATUS, type TakeoverConversationParams, TakeoverConversationUseCase, type TicketStoreInterface, type TranscribeAudioDependencies, type TranscribeAudioParams, type TranscribeAudioResult, TranscribeAudioUseCase, type TranscriptionPolicy, type TranscriptionPolicyDefaults, type TranscriptionPolicyResolver, type TranscriptionStatus, type UpdateFlowMediaParams, type UpdateQuickReplyParams, type UpdateQuickReplyParams$1 as UpdateQuickReplyRowParams, UpdateQuickReplyUseCase, WhatsAppChannelAdapter, buildFlowChoiceMessage, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createMetaWhatsAppQuickReplyRoutes, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isChoiceNode, isRetriableTranscriptionError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, quickReplies, readFlowInbound, redeemSseTicket, resolveFailureStatus, resolveFlowAnswer, resolveFlowConfigText, resolveFlowTimeZone, runMetaWhatsAppMigrations, sessions, settings, toQuickReplyView, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };