@adatechnology/meta-whatsapp-module 0.12.0 → 0.13.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 +90 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +43 -1
- package/dist/index.d.ts +43 -1
- package/dist/index.js +79 -9
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -224,6 +224,14 @@ whatsapp.flows!.registerDynamicChoiceProvider('free_slots', async ({ context, pa
|
|
|
224
224
|
`'duplicate'` sem reenviar nem reavisar a equipe. Erro depois dessa escrita **não sobe** — vai para
|
|
225
225
|
`onFlowRunnerError` (ou é descartado sem o gancho) e a conversa fica no último ponto gravado. Erro
|
|
226
226
|
antes dela (leitura do grafo, banco fora) sobe, e a retentativa é segura.
|
|
227
|
+
- **Retentativa do envio (`sendRetry`).** Cada mensagem do turno é retentada sozinha (padrão 3 tentativas, espera
|
|
228
|
+
500 ms e 1 s, teto de 5 s), então o que já saiu nunca é reenviado. Só repete falha de rede antes de a Meta receber
|
|
229
|
+
a mensagem (`isTransientSendError`); recusa da Meta, erro de banco depois do envio e janela expirada sobem na
|
|
230
|
+
primeira vez. Timeout **não** repete por padrão (a Meta pode ter aceitado e a Cloud API não tem chave de
|
|
231
|
+
idempotência); quem prefere repetir passa `sendRetry.shouldRetry`. As esperas rodam com o lock da conversa preso,
|
|
232
|
+
por isso o total é curto. Esgotadas as tentativas, o erro segue para `onFlowRunnerError`, agora com
|
|
233
|
+
`details.send = { attempts, messageKind, isTransient }` para o host avisar a equipe. Não cobre a mensagem do
|
|
234
|
+
encaminhamento (`handoff`) nem mídia de ação.
|
|
227
235
|
- **Fuso obrigatório.** `timeZone` (ou `handoff.businessHours.timeZone`, quando fixo) define "hoje";
|
|
228
236
|
sem ele o módulo falha na montagem. Servidor em UTC aceitaria "hoje" errado entre 21h e meia-noite.
|
|
229
237
|
- **Variáveis do host vencem.** Em `{{chave}}`, `resolveVariables`, `contactName` e `contactFirstName`
|
package/dist/index.cjs
CHANGED
|
@@ -84,8 +84,8 @@ __export(index_exports, {
|
|
|
84
84
|
TakeoverConversationUseCase: () => TakeoverConversationUseCase,
|
|
85
85
|
TranscribeAudioUseCase: () => TranscribeAudioUseCase,
|
|
86
86
|
UpdateQuickReplyUseCase: () => UpdateQuickReplyUseCase,
|
|
87
|
-
WEBHOOK_CLAIM_TTL_SECONDS: () =>
|
|
88
|
-
WEBHOOK_NONCE_TTL_SECONDS: () =>
|
|
87
|
+
WEBHOOK_CLAIM_TTL_SECONDS: () => import_meta_graph_core4.WEBHOOK_CLAIM_TTL_SECONDS,
|
|
88
|
+
WEBHOOK_NONCE_TTL_SECONDS: () => import_meta_graph_core4.WEBHOOK_NONCE_TTL_SECONDS,
|
|
89
89
|
WhatsAppChannelAdapter: () => WhatsAppChannelAdapter,
|
|
90
90
|
buildFlowChoiceMessage: () => buildFlowChoiceMessage,
|
|
91
91
|
buildInboundJobId: () => buildInboundJobId,
|
|
@@ -103,6 +103,7 @@ __export(index_exports, {
|
|
|
103
103
|
isAudioMimeType: () => isAudioMimeType,
|
|
104
104
|
isChoiceNode: () => isChoiceNode,
|
|
105
105
|
isRetriableTranscriptionError: () => isRetriableTranscriptionError,
|
|
106
|
+
isTransientSendError: () => isTransientSendError,
|
|
106
107
|
isUnsupportedTranscriptionError: () => isUnsupportedTranscriptionError,
|
|
107
108
|
issueSseTicket: () => issueSseTicket,
|
|
108
109
|
messages: () => messages,
|
|
@@ -2457,6 +2458,9 @@ var import_meta_whatsapp_contracts12 = require("@adatechnology/meta-whatsapp-con
|
|
|
2457
2458
|
var DEFAULT_START_FLOW_KEY = "main";
|
|
2458
2459
|
var DEFAULT_MAX_INVALID_ANSWERS = 2;
|
|
2459
2460
|
var DEFAULT_MAX_CROSS_FLOW_JUMPS = 5;
|
|
2461
|
+
var DEFAULT_SEND_RETRY_MAX_ATTEMPTS = 3;
|
|
2462
|
+
var DEFAULT_SEND_RETRY_BASE_DELAY_MS = 500;
|
|
2463
|
+
var DEFAULT_SEND_RETRY_MAX_DELAY_MS = 5e3;
|
|
2460
2464
|
var DEFAULT_FLOW_TEXT = {
|
|
2461
2465
|
FALLBACK: "N\xE3o entendi. Pode responder de novo?",
|
|
2462
2466
|
CHOICE_PROMPT: "Escolha uma op\xE7\xE3o:",
|
|
@@ -2837,6 +2841,47 @@ async function resolveFlowConfigText(params) {
|
|
|
2837
2841
|
}
|
|
2838
2842
|
__name(resolveFlowConfigText, "resolveFlowConfigText");
|
|
2839
2843
|
|
|
2844
|
+
// src/flows/sendWithRetry.ts
|
|
2845
|
+
var import_meta_graph_core2 = require("@adatechnology/meta-graph-core");
|
|
2846
|
+
function isTransientSendError(error) {
|
|
2847
|
+
return error instanceof import_meta_graph_core2.WhatsAppConnectionError;
|
|
2848
|
+
}
|
|
2849
|
+
__name(isTransientSendError, "isTransientSendError");
|
|
2850
|
+
var sleepFor = /* @__PURE__ */ __name((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)), "sleepFor");
|
|
2851
|
+
var SendRetriesExhausted = class {
|
|
2852
|
+
static {
|
|
2853
|
+
__name(this, "SendRetriesExhausted");
|
|
2854
|
+
}
|
|
2855
|
+
error;
|
|
2856
|
+
attempts;
|
|
2857
|
+
isTransient;
|
|
2858
|
+
constructor(error, attempts, isTransient) {
|
|
2859
|
+
this.error = error;
|
|
2860
|
+
this.attempts = attempts;
|
|
2861
|
+
this.isTransient = isTransient;
|
|
2862
|
+
}
|
|
2863
|
+
};
|
|
2864
|
+
async function sendWithRetry(send, config = {}) {
|
|
2865
|
+
const maxAttempts = Math.max(1, config.maxAttempts ?? DEFAULT_SEND_RETRY_MAX_ATTEMPTS);
|
|
2866
|
+
const baseDelay = config.baseDelayMs ?? DEFAULT_SEND_RETRY_BASE_DELAY_MS;
|
|
2867
|
+
const maxDelay = config.maxDelayMs ?? DEFAULT_SEND_RETRY_MAX_DELAY_MS;
|
|
2868
|
+
const shouldRetry = config.shouldRetry ?? isTransientSendError;
|
|
2869
|
+
const sleep = config.sleep ?? sleepFor;
|
|
2870
|
+
for (let attempt = 1; ; attempt++) {
|
|
2871
|
+
try {
|
|
2872
|
+
await send();
|
|
2873
|
+
return {
|
|
2874
|
+
attempts: attempt
|
|
2875
|
+
};
|
|
2876
|
+
} catch (error) {
|
|
2877
|
+
const isTransient = shouldRetry(error);
|
|
2878
|
+
if (!isTransient || attempt >= maxAttempts) throw new SendRetriesExhausted(error, attempt, isTransient);
|
|
2879
|
+
await sleep(Math.min(baseDelay * 2 ** (attempt - 1), maxDelay));
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
}
|
|
2883
|
+
__name(sendWithRetry, "sendWithRetry");
|
|
2884
|
+
|
|
2840
2885
|
// src/flows/FlowRunner.ts
|
|
2841
2886
|
function contactVariables(profileName) {
|
|
2842
2887
|
if (!profileName) return {};
|
|
@@ -2866,6 +2911,8 @@ var FlowRunner = class {
|
|
|
2866
2911
|
// Variáveis da mensagem em curso, por sessão: é como a action `handoff` (que só recebe a sessão)
|
|
2867
2912
|
// enxerga o nome do contato sem que ele precise ir para o contexto gravado.
|
|
2868
2913
|
turnVariables = /* @__PURE__ */ new WeakMap();
|
|
2914
|
+
// Erro de envio já sem retentativa → o que se tentou, para `report` entregar ao host sem trocar o erro.
|
|
2915
|
+
sendFailures = /* @__PURE__ */ new WeakMap();
|
|
2869
2916
|
constructor(dependencies) {
|
|
2870
2917
|
this.dependencies = dependencies;
|
|
2871
2918
|
this.renderer = new FlowQuestionRenderer(dependencies.config);
|
|
@@ -3360,6 +3407,10 @@ var FlowRunner = class {
|
|
|
3360
3407
|
body
|
|
3361
3408
|
});
|
|
3362
3409
|
}
|
|
3410
|
+
/**
|
|
3411
|
+
* Cada mensagem é retentada sozinha (ver `sendWithRetry`): o que já saiu neste turno não é reenviado.
|
|
3412
|
+
* Esgotadas as tentativas, o erro original sobe como antes e o `report` ganha `details.send`.
|
|
3413
|
+
*/
|
|
3363
3414
|
async send(turn, message) {
|
|
3364
3415
|
const common = {
|
|
3365
3416
|
companyId: turn.companyId,
|
|
@@ -3367,14 +3418,29 @@ var FlowRunner = class {
|
|
|
3367
3418
|
sender: "bot",
|
|
3368
3419
|
startState: this.dependencies.startState
|
|
3369
3420
|
};
|
|
3370
|
-
|
|
3371
|
-
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
|
|
3375
|
-
|
|
3376
|
-
|
|
3377
|
-
|
|
3421
|
+
const deliver = /* @__PURE__ */ __name(async () => {
|
|
3422
|
+
if (message.kind === "text") await this.dependencies.sendMessage.sendText({
|
|
3423
|
+
...common,
|
|
3424
|
+
body: message.body
|
|
3425
|
+
});
|
|
3426
|
+
else await this.dependencies.sendMessage.sendInteractive({
|
|
3427
|
+
...common,
|
|
3428
|
+
interactive: message.interactive
|
|
3429
|
+
});
|
|
3430
|
+
}, "deliver");
|
|
3431
|
+
try {
|
|
3432
|
+
await sendWithRetry(deliver, this.dependencies.config.sendRetry);
|
|
3433
|
+
} catch (failure) {
|
|
3434
|
+
if (!(failure instanceof SendRetriesExhausted)) throw failure;
|
|
3435
|
+
if (typeof failure.error === "object" && failure.error !== null) {
|
|
3436
|
+
this.sendFailures.set(failure.error, {
|
|
3437
|
+
attempts: failure.attempts,
|
|
3438
|
+
messageKind: message.kind,
|
|
3439
|
+
isTransient: failure.isTransient
|
|
3440
|
+
});
|
|
3441
|
+
}
|
|
3442
|
+
throw failure.error;
|
|
3443
|
+
}
|
|
3378
3444
|
}
|
|
3379
3445
|
save(turn, progress) {
|
|
3380
3446
|
const runtime = runtimeOf(progress.context);
|
|
@@ -3402,12 +3468,16 @@ var FlowRunner = class {
|
|
|
3402
3468
|
* ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
|
|
3403
3469
|
*/
|
|
3404
3470
|
async report(turn, flowKey, nodeId, stage, error) {
|
|
3471
|
+
const send = typeof error === "object" && error !== null ? this.sendFailures.get(error) : void 0;
|
|
3405
3472
|
const details = {
|
|
3406
3473
|
companyId: turn.companyId,
|
|
3407
3474
|
whatsappNumber: turn.session.whatsappNumber,
|
|
3408
3475
|
flowKey,
|
|
3409
3476
|
nodeId,
|
|
3410
|
-
stage
|
|
3477
|
+
stage,
|
|
3478
|
+
...send ? {
|
|
3479
|
+
send
|
|
3480
|
+
} : {}
|
|
3411
3481
|
};
|
|
3412
3482
|
try {
|
|
3413
3483
|
await this.dependencies.hooks?.onFlowRunnerError?.(error, details);
|
|
@@ -3850,7 +3920,7 @@ var FlowMediaIdRepository = class {
|
|
|
3850
3920
|
};
|
|
3851
3921
|
|
|
3852
3922
|
// src/channel/WhatsAppChannelAdapter.ts
|
|
3853
|
-
var
|
|
3923
|
+
var import_meta_graph_core3 = require("@adatechnology/meta-graph-core");
|
|
3854
3924
|
var import_meta_whatsapp_contracts19 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3855
3925
|
|
|
3856
3926
|
// src/channel/previewMedia.ts
|
|
@@ -3878,7 +3948,7 @@ var WhatsAppChannelAdapter = class {
|
|
|
3878
3948
|
try {
|
|
3879
3949
|
return await operation();
|
|
3880
3950
|
} catch (error) {
|
|
3881
|
-
if (error instanceof
|
|
3951
|
+
if (error instanceof import_meta_graph_core3.WhatsAppWindowExpiredError) throw new import_meta_whatsapp_contracts19.WindowExpiredError();
|
|
3882
3952
|
throw error;
|
|
3883
3953
|
}
|
|
3884
3954
|
}
|
|
@@ -3997,31 +4067,31 @@ var WhatsAppChannelAdapter = class {
|
|
|
3997
4067
|
var import_meta_whatsapp_contracts22 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3998
4068
|
|
|
3999
4069
|
// src/channel/webhookSecurity.ts
|
|
4000
|
-
var
|
|
4070
|
+
var import_meta_graph_core4 = require("@adatechnology/meta-graph-core");
|
|
4001
4071
|
var import_meta_whatsapp_contracts20 = require("@adatechnology/meta-whatsapp-contracts");
|
|
4002
4072
|
var WEBHOOK_NONCE_NAMESPACE = "meta-whatsapp";
|
|
4003
4073
|
function verifyWebhookChallenge(params) {
|
|
4004
|
-
if (!(0,
|
|
4074
|
+
if (!(0, import_meta_graph_core4.isValidWebhookChallenge)(params)) throw new import_meta_whatsapp_contracts20.InvalidWebhookSignatureError();
|
|
4005
4075
|
return params.challenge;
|
|
4006
4076
|
}
|
|
4007
4077
|
__name(verifyWebhookChallenge, "verifyWebhookChallenge");
|
|
4008
4078
|
function verifyWebhookSignature(params) {
|
|
4009
|
-
if (!(0,
|
|
4079
|
+
if (!(0, import_meta_graph_core4.isValidWebhookSignature)(params)) throw new import_meta_whatsapp_contracts20.InvalidWebhookSignatureError();
|
|
4010
4080
|
}
|
|
4011
4081
|
__name(verifyWebhookSignature, "verifyWebhookSignature");
|
|
4012
4082
|
function deliveryKey(signatureHeader) {
|
|
4013
|
-
return (0,
|
|
4083
|
+
return (0, import_meta_graph_core4.buildWebhookDeliveryKey)({
|
|
4014
4084
|
namespace: WEBHOOK_NONCE_NAMESPACE,
|
|
4015
4085
|
signatureHeader
|
|
4016
4086
|
});
|
|
4017
4087
|
}
|
|
4018
4088
|
__name(deliveryKey, "deliveryKey");
|
|
4019
4089
|
async function claimWebhookDelivery(params) {
|
|
4020
|
-
return params.nonceStore.setIfAbsent(deliveryKey(params.signatureHeader), params.ttlSeconds ??
|
|
4090
|
+
return params.nonceStore.setIfAbsent(deliveryKey(params.signatureHeader), params.ttlSeconds ?? import_meta_graph_core4.WEBHOOK_CLAIM_TTL_SECONDS);
|
|
4021
4091
|
}
|
|
4022
4092
|
__name(claimWebhookDelivery, "claimWebhookDelivery");
|
|
4023
4093
|
async function confirmWebhookDelivery(params) {
|
|
4024
|
-
await params.nonceStore.confirm?.(deliveryKey(params.signatureHeader), params.ttlSeconds ??
|
|
4094
|
+
await params.nonceStore.confirm?.(deliveryKey(params.signatureHeader), params.ttlSeconds ?? import_meta_graph_core4.WEBHOOK_NONCE_TTL_SECONDS);
|
|
4025
4095
|
}
|
|
4026
4096
|
__name(confirmWebhookDelivery, "confirmWebhookDelivery");
|
|
4027
4097
|
|
|
@@ -5230,6 +5300,7 @@ __name(createMetaWhatsAppQuickReplyRoutes, "createMetaWhatsAppQuickReplyRoutes")
|
|
|
5230
5300
|
isAudioMimeType,
|
|
5231
5301
|
isChoiceNode,
|
|
5232
5302
|
isRetriableTranscriptionError,
|
|
5303
|
+
isTransientSendError,
|
|
5233
5304
|
isUnsupportedTranscriptionError,
|
|
5234
5305
|
issueSseTicket,
|
|
5235
5306
|
messages,
|