@adatechnology/meta-whatsapp-module 0.12.0 → 0.14.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/README.md +8 -0
- package/dist/index.cjs +102 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +53 -1
- package/dist/index.d.ts +53 -1
- package/dist/index.js +91 -11
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.cts
CHANGED
|
@@ -1680,6 +1680,14 @@ interface ListMessagesParams$1 {
|
|
|
1680
1680
|
sessionId: string;
|
|
1681
1681
|
limit?: number;
|
|
1682
1682
|
before?: string;
|
|
1683
|
+
/**
|
|
1684
|
+
* Id da mensagem mais antiga que o cliente já tem: junto com `before`, forma o cursor composto
|
|
1685
|
+
* `(created_at, id)`, na mesma ordem da listagem. Só voltam as estritamente anteriores a ela, então
|
|
1686
|
+
* mensagens no mesmo instante da fronteira não somem nem se repetem. O `created_at` do cursor é lido da
|
|
1687
|
+
* própria linha (microssegundos), não do `before` (milissegundos). Id desconhecido ou que não é UUID cai no
|
|
1688
|
+
* `before`.
|
|
1689
|
+
*/
|
|
1690
|
+
beforeId?: string;
|
|
1683
1691
|
}
|
|
1684
1692
|
interface SaveTranscriptionByWaMessageIdParams extends Omit<SaveTranscriptionParams, 'messageId'> {
|
|
1685
1693
|
/**
|
|
@@ -2101,6 +2109,8 @@ type ListMessagesParams = {
|
|
|
2101
2109
|
whatsappNumber: string;
|
|
2102
2110
|
limit?: number;
|
|
2103
2111
|
before?: string;
|
|
2112
|
+
/** Desempate do cursor `before` (ver `MessageRepository.ListMessagesParams.beforeId`). */
|
|
2113
|
+
beforeId?: string;
|
|
2104
2114
|
};
|
|
2105
2115
|
declare class ListMessagesUseCase {
|
|
2106
2116
|
private readonly sessionRepository;
|
|
@@ -2561,6 +2571,23 @@ type FlowVariablesResolver = (params: {
|
|
|
2561
2571
|
readonly session: ConversationSession;
|
|
2562
2572
|
readonly profileName?: string;
|
|
2563
2573
|
}) => Promise<Readonly<Record<string, unknown>>>;
|
|
2574
|
+
/**
|
|
2575
|
+
* Retentativa do envio de saída do robô (cada mensagem do turno, uma a uma). Só repete falha em que a
|
|
2576
|
+
* mensagem não chegou à Meta (ver `isTransientSendError`); vale a pena porque o turno já foi
|
|
2577
|
+
* reivindicado e o cliente, sem isto, ficaria sem resposta até escrever de novo.
|
|
2578
|
+
*/
|
|
2579
|
+
type FlowSendRetryConfig = {
|
|
2580
|
+
/** Tentativas por mensagem, contando a primeira. Padrão 3; 1 desliga a retentativa. */
|
|
2581
|
+
readonly maxAttempts?: number;
|
|
2582
|
+
/** Espera antes da 2ª tentativa; dobra a cada falha. Padrão 500 ms. */
|
|
2583
|
+
readonly baseDelayMs?: number;
|
|
2584
|
+
/** Teto da espera. Padrão 5000 ms. */
|
|
2585
|
+
readonly maxDelayMs?: number;
|
|
2586
|
+
/** Decide se a falha vale outra tentativa. Padrão: falha de rede (`isTransientSendError`). */
|
|
2587
|
+
readonly shouldRetry?: (error: unknown) => boolean;
|
|
2588
|
+
/** Espera injetável para teste. */
|
|
2589
|
+
readonly sleep?: (milliseconds: number) => Promise<void>;
|
|
2590
|
+
};
|
|
2564
2591
|
type FlowRunnerConfig = {
|
|
2565
2592
|
/** Fluxo de quem chega sem conversa em andamento. Padrão `main`. */
|
|
2566
2593
|
readonly startFlowKey?: string;
|
|
@@ -2602,6 +2629,8 @@ type FlowRunnerConfig = {
|
|
|
2602
2629
|
readonly dynamicChoiceProviders?: Readonly<Record<string, DynamicChoiceProvider>>;
|
|
2603
2630
|
/** Saltos `flow:` seguidos numa mesma mensagem antes de desistir (protege de ciclo entre fluxos). Padrão 5. */
|
|
2604
2631
|
readonly maxCrossFlowJumps?: number;
|
|
2632
|
+
/** Retentativa do envio de saída. Ausente, valem os padrões de `FlowSendRetryConfig`. */
|
|
2633
|
+
readonly sendRetry?: FlowSendRetryConfig;
|
|
2605
2634
|
/** Relógio injetável para teste. */
|
|
2606
2635
|
readonly now?: () => Date;
|
|
2607
2636
|
};
|
|
@@ -2728,6 +2757,7 @@ declare class FlowRunner {
|
|
|
2728
2757
|
private readonly renderer;
|
|
2729
2758
|
private readonly timeZone;
|
|
2730
2759
|
private readonly turnVariables;
|
|
2760
|
+
private readonly sendFailures;
|
|
2731
2761
|
constructor(dependencies: FlowRunnerDependencies);
|
|
2732
2762
|
registerDynamicChoiceProvider(key: string, provider: DynamicChoiceProvider): void;
|
|
2733
2763
|
/**
|
|
@@ -2779,6 +2809,10 @@ declare class FlowRunner {
|
|
|
2779
2809
|
/** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
|
|
2780
2810
|
private awaitAnswer;
|
|
2781
2811
|
private say;
|
|
2812
|
+
/**
|
|
2813
|
+
* Cada mensagem é retentada sozinha (ver `sendWithRetry`): o que já saiu neste turno não é reenviado.
|
|
2814
|
+
* Esgotadas as tentativas, o erro original sobe como antes e o `report` ganha `details.send`.
|
|
2815
|
+
*/
|
|
2782
2816
|
private send;
|
|
2783
2817
|
private save;
|
|
2784
2818
|
private reportMissingFlow;
|
|
@@ -3696,6 +3730,24 @@ declare function redeemSseTicket(store: TicketStoreInterface, ticket: string): P
|
|
|
3696
3730
|
whatsappNumber: string;
|
|
3697
3731
|
} | null>;
|
|
3698
3732
|
|
|
3733
|
+
/**
|
|
3734
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3735
|
+
*
|
|
3736
|
+
* Retentativa de UM envio de saída do robô, com limite e backoff exponencial.
|
|
3737
|
+
*
|
|
3738
|
+
* Cada mensagem do turno é retentada sozinha: se a segunda falha, a primeira (já entregue) não sai de
|
|
3739
|
+
* novo. Só se repete falha em que a Meta nunca recebeu a mensagem; o resto (recusa da Meta, erro de
|
|
3740
|
+
* banco depois do envio, janela expirada) sobe na primeira vez — repetir duplicaria ou falharia igual.
|
|
3741
|
+
*/
|
|
3742
|
+
|
|
3743
|
+
/**
|
|
3744
|
+
* Padrão de `FlowSendRetryConfig.shouldRetry`: falha de rede antes de a requisição ser entregue.
|
|
3745
|
+
* Timeout fica de fora de propósito: a Meta pode ter aceitado a mensagem e a Cloud API não tem chave
|
|
3746
|
+
* de idempotência, então repetir arriscaria mandar duas vezes. O host que prefere repetir passa o
|
|
3747
|
+
* próprio `shouldRetry`.
|
|
3748
|
+
*/
|
|
3749
|
+
declare function isTransientSendError(error: unknown): boolean;
|
|
3750
|
+
|
|
3699
3751
|
/**
|
|
3700
3752
|
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3701
3753
|
*
|
|
@@ -3985,4 +4037,4 @@ type CreateMetaWhatsAppQuickReplyRoutesParams = {
|
|
|
3985
4037
|
*/
|
|
3986
4038
|
declare function createMetaWhatsAppQuickReplyRoutes(params: CreateMetaWhatsAppQuickReplyRoutesParams): ModuleRouteTable;
|
|
3987
4039
|
|
|
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 };
|
|
4040
|
+
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 FlowSendRetryConfig, 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, isTransientSendError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, quickReplies, readFlowInbound, redeemSseTicket, resolveFailureStatus, resolveFlowAnswer, resolveFlowConfigText, resolveFlowTimeZone, runMetaWhatsAppMigrations, sessions, settings, toQuickReplyView, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
|
package/dist/index.d.ts
CHANGED
|
@@ -1680,6 +1680,14 @@ interface ListMessagesParams$1 {
|
|
|
1680
1680
|
sessionId: string;
|
|
1681
1681
|
limit?: number;
|
|
1682
1682
|
before?: string;
|
|
1683
|
+
/**
|
|
1684
|
+
* Id da mensagem mais antiga que o cliente já tem: junto com `before`, forma o cursor composto
|
|
1685
|
+
* `(created_at, id)`, na mesma ordem da listagem. Só voltam as estritamente anteriores a ela, então
|
|
1686
|
+
* mensagens no mesmo instante da fronteira não somem nem se repetem. O `created_at` do cursor é lido da
|
|
1687
|
+
* própria linha (microssegundos), não do `before` (milissegundos). Id desconhecido ou que não é UUID cai no
|
|
1688
|
+
* `before`.
|
|
1689
|
+
*/
|
|
1690
|
+
beforeId?: string;
|
|
1683
1691
|
}
|
|
1684
1692
|
interface SaveTranscriptionByWaMessageIdParams extends Omit<SaveTranscriptionParams, 'messageId'> {
|
|
1685
1693
|
/**
|
|
@@ -2101,6 +2109,8 @@ type ListMessagesParams = {
|
|
|
2101
2109
|
whatsappNumber: string;
|
|
2102
2110
|
limit?: number;
|
|
2103
2111
|
before?: string;
|
|
2112
|
+
/** Desempate do cursor `before` (ver `MessageRepository.ListMessagesParams.beforeId`). */
|
|
2113
|
+
beforeId?: string;
|
|
2104
2114
|
};
|
|
2105
2115
|
declare class ListMessagesUseCase {
|
|
2106
2116
|
private readonly sessionRepository;
|
|
@@ -2561,6 +2571,23 @@ type FlowVariablesResolver = (params: {
|
|
|
2561
2571
|
readonly session: ConversationSession;
|
|
2562
2572
|
readonly profileName?: string;
|
|
2563
2573
|
}) => Promise<Readonly<Record<string, unknown>>>;
|
|
2574
|
+
/**
|
|
2575
|
+
* Retentativa do envio de saída do robô (cada mensagem do turno, uma a uma). Só repete falha em que a
|
|
2576
|
+
* mensagem não chegou à Meta (ver `isTransientSendError`); vale a pena porque o turno já foi
|
|
2577
|
+
* reivindicado e o cliente, sem isto, ficaria sem resposta até escrever de novo.
|
|
2578
|
+
*/
|
|
2579
|
+
type FlowSendRetryConfig = {
|
|
2580
|
+
/** Tentativas por mensagem, contando a primeira. Padrão 3; 1 desliga a retentativa. */
|
|
2581
|
+
readonly maxAttempts?: number;
|
|
2582
|
+
/** Espera antes da 2ª tentativa; dobra a cada falha. Padrão 500 ms. */
|
|
2583
|
+
readonly baseDelayMs?: number;
|
|
2584
|
+
/** Teto da espera. Padrão 5000 ms. */
|
|
2585
|
+
readonly maxDelayMs?: number;
|
|
2586
|
+
/** Decide se a falha vale outra tentativa. Padrão: falha de rede (`isTransientSendError`). */
|
|
2587
|
+
readonly shouldRetry?: (error: unknown) => boolean;
|
|
2588
|
+
/** Espera injetável para teste. */
|
|
2589
|
+
readonly sleep?: (milliseconds: number) => Promise<void>;
|
|
2590
|
+
};
|
|
2564
2591
|
type FlowRunnerConfig = {
|
|
2565
2592
|
/** Fluxo de quem chega sem conversa em andamento. Padrão `main`. */
|
|
2566
2593
|
readonly startFlowKey?: string;
|
|
@@ -2602,6 +2629,8 @@ type FlowRunnerConfig = {
|
|
|
2602
2629
|
readonly dynamicChoiceProviders?: Readonly<Record<string, DynamicChoiceProvider>>;
|
|
2603
2630
|
/** Saltos `flow:` seguidos numa mesma mensagem antes de desistir (protege de ciclo entre fluxos). Padrão 5. */
|
|
2604
2631
|
readonly maxCrossFlowJumps?: number;
|
|
2632
|
+
/** Retentativa do envio de saída. Ausente, valem os padrões de `FlowSendRetryConfig`. */
|
|
2633
|
+
readonly sendRetry?: FlowSendRetryConfig;
|
|
2605
2634
|
/** Relógio injetável para teste. */
|
|
2606
2635
|
readonly now?: () => Date;
|
|
2607
2636
|
};
|
|
@@ -2728,6 +2757,7 @@ declare class FlowRunner {
|
|
|
2728
2757
|
private readonly renderer;
|
|
2729
2758
|
private readonly timeZone;
|
|
2730
2759
|
private readonly turnVariables;
|
|
2760
|
+
private readonly sendFailures;
|
|
2731
2761
|
constructor(dependencies: FlowRunnerDependencies);
|
|
2732
2762
|
registerDynamicChoiceProvider(key: string, provider: DynamicChoiceProvider): void;
|
|
2733
2763
|
/**
|
|
@@ -2779,6 +2809,10 @@ declare class FlowRunner {
|
|
|
2779
2809
|
/** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
|
|
2780
2810
|
private awaitAnswer;
|
|
2781
2811
|
private say;
|
|
2812
|
+
/**
|
|
2813
|
+
* Cada mensagem é retentada sozinha (ver `sendWithRetry`): o que já saiu neste turno não é reenviado.
|
|
2814
|
+
* Esgotadas as tentativas, o erro original sobe como antes e o `report` ganha `details.send`.
|
|
2815
|
+
*/
|
|
2782
2816
|
private send;
|
|
2783
2817
|
private save;
|
|
2784
2818
|
private reportMissingFlow;
|
|
@@ -3696,6 +3730,24 @@ declare function redeemSseTicket(store: TicketStoreInterface, ticket: string): P
|
|
|
3696
3730
|
whatsappNumber: string;
|
|
3697
3731
|
} | null>;
|
|
3698
3732
|
|
|
3733
|
+
/**
|
|
3734
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3735
|
+
*
|
|
3736
|
+
* Retentativa de UM envio de saída do robô, com limite e backoff exponencial.
|
|
3737
|
+
*
|
|
3738
|
+
* Cada mensagem do turno é retentada sozinha: se a segunda falha, a primeira (já entregue) não sai de
|
|
3739
|
+
* novo. Só se repete falha em que a Meta nunca recebeu a mensagem; o resto (recusa da Meta, erro de
|
|
3740
|
+
* banco depois do envio, janela expirada) sobe na primeira vez — repetir duplicaria ou falharia igual.
|
|
3741
|
+
*/
|
|
3742
|
+
|
|
3743
|
+
/**
|
|
3744
|
+
* Padrão de `FlowSendRetryConfig.shouldRetry`: falha de rede antes de a requisição ser entregue.
|
|
3745
|
+
* Timeout fica de fora de propósito: a Meta pode ter aceitado a mensagem e a Cloud API não tem chave
|
|
3746
|
+
* de idempotência, então repetir arriscaria mandar duas vezes. O host que prefere repetir passa o
|
|
3747
|
+
* próprio `shouldRetry`.
|
|
3748
|
+
*/
|
|
3749
|
+
declare function isTransientSendError(error: unknown): boolean;
|
|
3750
|
+
|
|
3699
3751
|
/**
|
|
3700
3752
|
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3701
3753
|
*
|
|
@@ -3985,4 +4037,4 @@ type CreateMetaWhatsAppQuickReplyRoutesParams = {
|
|
|
3985
4037
|
*/
|
|
3986
4038
|
declare function createMetaWhatsAppQuickReplyRoutes(params: CreateMetaWhatsAppQuickReplyRoutesParams): ModuleRouteTable;
|
|
3987
4039
|
|
|
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 };
|
|
4040
|
+
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 FlowSendRetryConfig, 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, isTransientSendError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, quickReplies, readFlowInbound, redeemSseTicket, resolveFailureStatus, resolveFlowAnswer, resolveFlowConfigText, resolveFlowTimeZone, runMetaWhatsAppMigrations, sessions, settings, toQuickReplyView, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
|
package/dist/index.js
CHANGED
|
@@ -578,6 +578,7 @@ import { and as and2, count, desc as desc2, eq as eq2, lt, sql as sql3 } from "d
|
|
|
578
578
|
var INBOUND_LOCATION_CONTENT = "\u{1F4CD} Localiza\xE7\xE3o";
|
|
579
579
|
|
|
580
580
|
// src/repositories/MessageRepository.ts
|
|
581
|
+
var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
581
582
|
var DEFAULT_LIMIT2 = 50;
|
|
582
583
|
var MessageRepository = class {
|
|
583
584
|
static {
|
|
@@ -750,7 +751,15 @@ var MessageRepository = class {
|
|
|
750
751
|
eq2(messages.companyId, params.companyId),
|
|
751
752
|
eq2(messages.sessionId, params.sessionId)
|
|
752
753
|
];
|
|
753
|
-
if (params.
|
|
754
|
+
if (params.beforeId && UUID_PATTERN.test(params.beforeId)) {
|
|
755
|
+
const compositeCursor = sql3`(${messages.createdAt}, ${messages.id}) < (
|
|
756
|
+
select cursor_row.created_at, cursor_row.id from ${messages} as cursor_row
|
|
757
|
+
where cursor_row.id = ${params.beforeId}
|
|
758
|
+
and cursor_row.company_id = ${params.companyId}
|
|
759
|
+
and cursor_row.session_id = ${params.sessionId}
|
|
760
|
+
)`;
|
|
761
|
+
conditions.push(params.before ? sql3`coalesce(${compositeCursor}, ${lt(messages.createdAt, new Date(params.before))})` : compositeCursor);
|
|
762
|
+
} else if (params.before) conditions.push(lt(messages.createdAt, new Date(params.before)));
|
|
754
763
|
const newestFirst = await this.db.select().from(messages).where(and2(...conditions)).orderBy(desc2(messages.createdAt), desc2(messages.id)).limit(params.limit ?? DEFAULT_LIMIT2);
|
|
755
764
|
return newestFirst.reverse();
|
|
756
765
|
}
|
|
@@ -1538,7 +1547,8 @@ var ListMessagesUseCase = class {
|
|
|
1538
1547
|
companyId: params.companyId,
|
|
1539
1548
|
sessionId: session.id,
|
|
1540
1549
|
limit: params.limit,
|
|
1541
|
-
before: params.before
|
|
1550
|
+
before: params.before,
|
|
1551
|
+
beforeId: params.beforeId
|
|
1542
1552
|
};
|
|
1543
1553
|
return this.messageRepository.listByConversation(repoParams);
|
|
1544
1554
|
}
|
|
@@ -2337,6 +2347,9 @@ import { matchFlowChoice, matchFlowKeywordRoute, validateFlowAnswer } from "@ada
|
|
|
2337
2347
|
var DEFAULT_START_FLOW_KEY = "main";
|
|
2338
2348
|
var DEFAULT_MAX_INVALID_ANSWERS = 2;
|
|
2339
2349
|
var DEFAULT_MAX_CROSS_FLOW_JUMPS = 5;
|
|
2350
|
+
var DEFAULT_SEND_RETRY_MAX_ATTEMPTS = 3;
|
|
2351
|
+
var DEFAULT_SEND_RETRY_BASE_DELAY_MS = 500;
|
|
2352
|
+
var DEFAULT_SEND_RETRY_MAX_DELAY_MS = 5e3;
|
|
2340
2353
|
var DEFAULT_FLOW_TEXT = {
|
|
2341
2354
|
FALLBACK: "N\xE3o entendi. Pode responder de novo?",
|
|
2342
2355
|
CHOICE_PROMPT: "Escolha uma op\xE7\xE3o:",
|
|
@@ -2717,6 +2730,47 @@ async function resolveFlowConfigText(params) {
|
|
|
2717
2730
|
}
|
|
2718
2731
|
__name(resolveFlowConfigText, "resolveFlowConfigText");
|
|
2719
2732
|
|
|
2733
|
+
// src/flows/sendWithRetry.ts
|
|
2734
|
+
import { WhatsAppConnectionError } from "@adatechnology/meta-graph-core";
|
|
2735
|
+
function isTransientSendError(error) {
|
|
2736
|
+
return error instanceof WhatsAppConnectionError;
|
|
2737
|
+
}
|
|
2738
|
+
__name(isTransientSendError, "isTransientSendError");
|
|
2739
|
+
var sleepFor = /* @__PURE__ */ __name((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)), "sleepFor");
|
|
2740
|
+
var SendRetriesExhausted = class {
|
|
2741
|
+
static {
|
|
2742
|
+
__name(this, "SendRetriesExhausted");
|
|
2743
|
+
}
|
|
2744
|
+
error;
|
|
2745
|
+
attempts;
|
|
2746
|
+
isTransient;
|
|
2747
|
+
constructor(error, attempts, isTransient) {
|
|
2748
|
+
this.error = error;
|
|
2749
|
+
this.attempts = attempts;
|
|
2750
|
+
this.isTransient = isTransient;
|
|
2751
|
+
}
|
|
2752
|
+
};
|
|
2753
|
+
async function sendWithRetry(send, config = {}) {
|
|
2754
|
+
const maxAttempts = Math.max(1, config.maxAttempts ?? DEFAULT_SEND_RETRY_MAX_ATTEMPTS);
|
|
2755
|
+
const baseDelay = config.baseDelayMs ?? DEFAULT_SEND_RETRY_BASE_DELAY_MS;
|
|
2756
|
+
const maxDelay = config.maxDelayMs ?? DEFAULT_SEND_RETRY_MAX_DELAY_MS;
|
|
2757
|
+
const shouldRetry = config.shouldRetry ?? isTransientSendError;
|
|
2758
|
+
const sleep = config.sleep ?? sleepFor;
|
|
2759
|
+
for (let attempt = 1; ; attempt++) {
|
|
2760
|
+
try {
|
|
2761
|
+
await send();
|
|
2762
|
+
return {
|
|
2763
|
+
attempts: attempt
|
|
2764
|
+
};
|
|
2765
|
+
} catch (error) {
|
|
2766
|
+
const isTransient = shouldRetry(error);
|
|
2767
|
+
if (!isTransient || attempt >= maxAttempts) throw new SendRetriesExhausted(error, attempt, isTransient);
|
|
2768
|
+
await sleep(Math.min(baseDelay * 2 ** (attempt - 1), maxDelay));
|
|
2769
|
+
}
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
__name(sendWithRetry, "sendWithRetry");
|
|
2773
|
+
|
|
2720
2774
|
// src/flows/FlowRunner.ts
|
|
2721
2775
|
function contactVariables(profileName) {
|
|
2722
2776
|
if (!profileName) return {};
|
|
@@ -2746,6 +2800,8 @@ var FlowRunner = class {
|
|
|
2746
2800
|
// Variáveis da mensagem em curso, por sessão: é como a action `handoff` (que só recebe a sessão)
|
|
2747
2801
|
// enxerga o nome do contato sem que ele precise ir para o contexto gravado.
|
|
2748
2802
|
turnVariables = /* @__PURE__ */ new WeakMap();
|
|
2803
|
+
// Erro de envio já sem retentativa → o que se tentou, para `report` entregar ao host sem trocar o erro.
|
|
2804
|
+
sendFailures = /* @__PURE__ */ new WeakMap();
|
|
2749
2805
|
constructor(dependencies) {
|
|
2750
2806
|
this.dependencies = dependencies;
|
|
2751
2807
|
this.renderer = new FlowQuestionRenderer(dependencies.config);
|
|
@@ -3240,6 +3296,10 @@ var FlowRunner = class {
|
|
|
3240
3296
|
body
|
|
3241
3297
|
});
|
|
3242
3298
|
}
|
|
3299
|
+
/**
|
|
3300
|
+
* Cada mensagem é retentada sozinha (ver `sendWithRetry`): o que já saiu neste turno não é reenviado.
|
|
3301
|
+
* Esgotadas as tentativas, o erro original sobe como antes e o `report` ganha `details.send`.
|
|
3302
|
+
*/
|
|
3243
3303
|
async send(turn, message) {
|
|
3244
3304
|
const common = {
|
|
3245
3305
|
companyId: turn.companyId,
|
|
@@ -3247,14 +3307,29 @@ var FlowRunner = class {
|
|
|
3247
3307
|
sender: "bot",
|
|
3248
3308
|
startState: this.dependencies.startState
|
|
3249
3309
|
};
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
3254
|
-
|
|
3255
|
-
|
|
3256
|
-
|
|
3257
|
-
|
|
3310
|
+
const deliver = /* @__PURE__ */ __name(async () => {
|
|
3311
|
+
if (message.kind === "text") await this.dependencies.sendMessage.sendText({
|
|
3312
|
+
...common,
|
|
3313
|
+
body: message.body
|
|
3314
|
+
});
|
|
3315
|
+
else await this.dependencies.sendMessage.sendInteractive({
|
|
3316
|
+
...common,
|
|
3317
|
+
interactive: message.interactive
|
|
3318
|
+
});
|
|
3319
|
+
}, "deliver");
|
|
3320
|
+
try {
|
|
3321
|
+
await sendWithRetry(deliver, this.dependencies.config.sendRetry);
|
|
3322
|
+
} catch (failure) {
|
|
3323
|
+
if (!(failure instanceof SendRetriesExhausted)) throw failure;
|
|
3324
|
+
if (typeof failure.error === "object" && failure.error !== null) {
|
|
3325
|
+
this.sendFailures.set(failure.error, {
|
|
3326
|
+
attempts: failure.attempts,
|
|
3327
|
+
messageKind: message.kind,
|
|
3328
|
+
isTransient: failure.isTransient
|
|
3329
|
+
});
|
|
3330
|
+
}
|
|
3331
|
+
throw failure.error;
|
|
3332
|
+
}
|
|
3258
3333
|
}
|
|
3259
3334
|
save(turn, progress) {
|
|
3260
3335
|
const runtime = runtimeOf(progress.context);
|
|
@@ -3282,12 +3357,16 @@ var FlowRunner = class {
|
|
|
3282
3357
|
* ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
|
|
3283
3358
|
*/
|
|
3284
3359
|
async report(turn, flowKey, nodeId, stage, error) {
|
|
3360
|
+
const send = typeof error === "object" && error !== null ? this.sendFailures.get(error) : void 0;
|
|
3285
3361
|
const details = {
|
|
3286
3362
|
companyId: turn.companyId,
|
|
3287
3363
|
whatsappNumber: turn.session.whatsappNumber,
|
|
3288
3364
|
flowKey,
|
|
3289
3365
|
nodeId,
|
|
3290
|
-
stage
|
|
3366
|
+
stage,
|
|
3367
|
+
...send ? {
|
|
3368
|
+
send
|
|
3369
|
+
} : {}
|
|
3291
3370
|
};
|
|
3292
3371
|
try {
|
|
3293
3372
|
await this.dependencies.hooks?.onFlowRunnerError?.(error, details);
|
|
@@ -5109,6 +5188,7 @@ export {
|
|
|
5109
5188
|
isAudioMimeType,
|
|
5110
5189
|
isChoiceNode,
|
|
5111
5190
|
isRetriableTranscriptionError,
|
|
5191
|
+
isTransientSendError,
|
|
5112
5192
|
isUnsupportedTranscriptionError,
|
|
5113
5193
|
issueSseTicket,
|
|
5114
5194
|
messages,
|