cdp-edge 2.3.9 → 2.5.2
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 +54 -4
- package/bin/cdp-edge.js +3 -2
- package/contracts/agent-versions.json +383 -83
- package/dist/commands/validate.js +248 -84
- package/dist/sdk/cdpTrack.js +2095 -0
- package/dist/sdk/cdpTrack.min.js +64 -0
- package/dist/sdk/install-snippet.html +10 -0
- package/extracted-skill/tracking-events-generator/agents/ab-ltv-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/ab-testing-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/attribution-agent.md +18 -18
- package/extracted-skill/tracking-events-generator/agents/bidding-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/bing-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/code-guardian-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/compliance-agent.md +5 -5
- package/extracted-skill/tracking-events-generator/agents/crm-integration-agent.md +10 -10
- package/extracted-skill/tracking-events-generator/agents/dashboard-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/database-agent.md +17 -25
- package/extracted-skill/tracking-events-generator/agents/debug-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/agents/devops-agent.md +18 -1
- package/extracted-skill/tracking-events-generator/agents/domain-setup-agent.md +5 -5
- package/extracted-skill/tracking-events-generator/agents/email-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/fingerprint-agent.md +4 -4
- package/extracted-skill/tracking-events-generator/agents/fraud-detection-agent.md +2 -0
- package/extracted-skill/tracking-events-generator/agents/google-agent.md +2 -2
- package/extracted-skill/tracking-events-generator/agents/intelligence-agent.md +23 -29
- package/extracted-skill/tracking-events-generator/agents/linkedin-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/localization-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/ltv-predictor-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/master-feedback-loop.md +16 -16
- package/extracted-skill/tracking-events-generator/agents/master-orchestrator.md +13 -13
- package/extracted-skill/tracking-events-generator/agents/memory-agent.md +14 -14
- package/extracted-skill/tracking-events-generator/agents/meta-agent.md +2 -2
- package/extracted-skill/tracking-events-generator/agents/ml-clustering-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/agents/page-analyzer.md +1 -0
- package/extracted-skill/tracking-events-generator/agents/performance-agent.md +12 -12
- package/extracted-skill/tracking-events-generator/agents/performance-optimization-agent.md +7 -7
- package/extracted-skill/tracking-events-generator/agents/pinterest-agent.md +6 -6
- package/extracted-skill/tracking-events-generator/agents/premium-tracking-intelligence-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/r2-setup-agent.md +8 -8
- package/extracted-skill/tracking-events-generator/agents/reddit-agent.md +7 -7
- package/extracted-skill/tracking-events-generator/agents/security-enterprise-agent.md +21 -21
- package/extracted-skill/tracking-events-generator/agents/server-tracking.md +15 -15
- package/extracted-skill/tracking-events-generator/agents/spotify-agent.md +6 -6
- package/extracted-skill/tracking-events-generator/agents/tiktok-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/tracking-plan-agent.md +5 -5
- package/extracted-skill/tracking-events-generator/agents/validator-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/agents/webhook-agent.md +4 -4
- package/extracted-skill/tracking-events-generator/agents/whatsapp-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/whatsapp-ctwa-setup-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/youtube-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/anti-blocking.js +1 -1
- package/extracted-skill/tracking-events-generator/cdpTrack.js +0 -10
- package/extracted-skill/tracking-events-generator/engagement-scoring.js +2 -2
- package/extracted-skill/tracking-events-generator/micro-events.js +1 -1
- package/extracted-skill/tracking-events-generator/tracking.config.js +3 -3
- package/package.json +5 -1
- package/scripts/build-sdk.js +106 -0
- package/server-edge-tracker/index.ts +93 -0
- package/server-edge-tracker/schema-utm.sql +5 -3
- package/server-edge-tracker/wrangler.toml +1 -1
- package/extracted-skill/tracking-events-generator/agents/intelligence-scheduling.md +0 -10
|
@@ -43,7 +43,7 @@ Browser (Cliente) Worker (Server-Side) APIs (Meta/Google/TikT
|
|
|
43
43
|
|
|
44
44
|
### 1.1 Token Bucket Algorithm
|
|
45
45
|
|
|
46
|
-
```
|
|
46
|
+
```typescript
|
|
47
47
|
// Rate limiting com token bucket
|
|
48
48
|
const RATE_LIMIT_CONFIG = {
|
|
49
49
|
// Limites por IP
|
|
@@ -127,7 +127,7 @@ const rateLimiters = {
|
|
|
127
127
|
|
|
128
128
|
### 1.2 Rate Limiting Middleware
|
|
129
129
|
|
|
130
|
-
```
|
|
130
|
+
```typescript
|
|
131
131
|
// Middleware de rate limiting
|
|
132
132
|
export async function applyRateLimiting(request, env) {
|
|
133
133
|
const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
|
|
@@ -260,7 +260,7 @@ export async function applyRateLimiting(request, env) {
|
|
|
260
260
|
|
|
261
261
|
### 1.3 Response Headers de Rate Limiting
|
|
262
262
|
|
|
263
|
-
```
|
|
263
|
+
```typescript
|
|
264
264
|
// Headers de resposta com informações de rate limiting
|
|
265
265
|
export function getRateLimitHeaders(checkResult) {
|
|
266
266
|
const headers = {
|
|
@@ -285,7 +285,7 @@ export function getRateLimitHeaders(checkResult) {
|
|
|
285
285
|
|
|
286
286
|
### 2.1 Blacklist e Whitelist de IPs
|
|
287
287
|
|
|
288
|
-
```
|
|
288
|
+
```typescript
|
|
289
289
|
// Configuração de IP blocking
|
|
290
290
|
const IP_BLOCKING_CONFIG = {
|
|
291
291
|
// Blacklist: IPs explicitamente bloqueados
|
|
@@ -396,7 +396,7 @@ CREATE INDEX IF NOT EXISTS idx_ip_violations_blocked ON ip_violations(blocked);
|
|
|
396
396
|
|
|
397
397
|
### 2.3 IP Blocking Middleware
|
|
398
398
|
|
|
399
|
-
```
|
|
399
|
+
```typescript
|
|
400
400
|
// Middleware de IP blocking
|
|
401
401
|
export async function checkIPBlocking(request, env) {
|
|
402
402
|
const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
|
|
@@ -621,7 +621,7 @@ async function blockIPAutomatically(ip, reason, count, env) {
|
|
|
621
621
|
|
|
622
622
|
### 3.1 Schema Validation (Joi)
|
|
623
623
|
|
|
624
|
-
```
|
|
624
|
+
```typescript
|
|
625
625
|
// Joi schema validation (via npm package)
|
|
626
626
|
import Joi from 'joi';
|
|
627
627
|
|
|
@@ -740,7 +740,7 @@ export async function validateEvent(eventData, eventName) {
|
|
|
740
740
|
|
|
741
741
|
### 3.2 Sanitização de Dados (Anti-XSS, Anti-Injection)
|
|
742
742
|
|
|
743
|
-
```
|
|
743
|
+
```typescript
|
|
744
744
|
// Sanitização de strings (anti-XSS)
|
|
745
745
|
export function sanitizeString(input) {
|
|
746
746
|
if (!input || typeof input !== 'string') {
|
|
@@ -929,7 +929,7 @@ export function sanitizePayload(eventData, eventName) {
|
|
|
929
929
|
|
|
930
930
|
CSRF é relevante nos **endpoints de webhook** (Hotmart, Kiwify, Ticto) onde um atacante pode forjar requisições. A proteção é HMAC-SHA256 por assinatura — cada plataforma assina o payload com um secret compartilhado.
|
|
931
931
|
|
|
932
|
-
```
|
|
932
|
+
```typescript
|
|
933
933
|
/**
|
|
934
934
|
* Verificação CSRF via HMAC-SHA256 para webhooks de plataformas de pagamento.
|
|
935
935
|
* Cada plataforma tem seu próprio header e algoritmo.
|
|
@@ -1026,7 +1026,7 @@ function timingSafeEqual(a, b) {
|
|
|
1026
1026
|
|
|
1027
1027
|
### 3.4 Middleware de Validação e Sanitização
|
|
1028
1028
|
|
|
1029
|
-
```
|
|
1029
|
+
```typescript
|
|
1030
1030
|
// Middleware de segurança completo
|
|
1031
1031
|
export async function applySecurityMiddleware(request, env) {
|
|
1032
1032
|
const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
|
|
@@ -1148,7 +1148,7 @@ export async function applySecurityMiddleware(request, env) {
|
|
|
1148
1148
|
|
|
1149
1149
|
### 4.1 Configuração de Encryption
|
|
1150
1150
|
|
|
1151
|
-
```
|
|
1151
|
+
```typescript
|
|
1152
1152
|
// Configuração de encryption
|
|
1153
1153
|
const ENCRYPTION_CONFIG = {
|
|
1154
1154
|
// Algoritmos de hash (para enviar às plataformas)
|
|
@@ -1186,7 +1186,7 @@ const ENCRYPTION_CONFIG = {
|
|
|
1186
1186
|
|
|
1187
1187
|
### 4.2 Hashing Functions (SHA256 - Web Crypto API)
|
|
1188
1188
|
|
|
1189
|
-
```
|
|
1189
|
+
```typescript
|
|
1190
1190
|
// Hashing de email
|
|
1191
1191
|
export async function hashEmail(email) {
|
|
1192
1192
|
if (!email) return null;
|
|
@@ -1303,7 +1303,7 @@ export async function hashCEP(cep) {
|
|
|
1303
1303
|
|
|
1304
1304
|
### 4.3 Encryption Functions (AES-256-GCM)
|
|
1305
1305
|
|
|
1306
|
-
```
|
|
1306
|
+
```typescript
|
|
1307
1307
|
// Encriptação de dados sensíveis
|
|
1308
1308
|
const encryptionKeys = new Map();
|
|
1309
1309
|
|
|
@@ -1447,7 +1447,7 @@ CREATE INDEX IF NOT EXISTS idx_audit_blocked ON audit_logs(blocked);
|
|
|
1447
1447
|
|
|
1448
1448
|
### 5.2 Tipos de Audit Log
|
|
1449
1449
|
|
|
1450
|
-
```
|
|
1450
|
+
```typescript
|
|
1451
1451
|
// Tipos de log de segurança
|
|
1452
1452
|
const AUDIT_LOG_TYPES = {
|
|
1453
1453
|
// Rate Limiting
|
|
@@ -1498,7 +1498,7 @@ const SEVERITY_LEVELS = {
|
|
|
1498
1498
|
|
|
1499
1499
|
### 5.3 Funções de Audit Logging
|
|
1500
1500
|
|
|
1501
|
-
```
|
|
1501
|
+
```typescript
|
|
1502
1502
|
// Log de evento de segurança
|
|
1503
1503
|
export async function logSecurityEvent(eventData, env) {
|
|
1504
1504
|
const {
|
|
@@ -1620,7 +1620,7 @@ export async function queryAuditLogs(filters = {}, env) {
|
|
|
1620
1620
|
|
|
1621
1621
|
### 6.1 Endpoint: `/api/security/rate-limit-status`
|
|
1622
1622
|
|
|
1623
|
-
```
|
|
1623
|
+
```typescript
|
|
1624
1624
|
export async function getRateLimitStatus(request, env) {
|
|
1625
1625
|
const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
|
|
1626
1626
|
|
|
@@ -1660,7 +1660,7 @@ export async function getRateLimitStatus(request, env) {
|
|
|
1660
1660
|
|
|
1661
1661
|
### 6.2 Endpoint: `/api/security/ip-status`
|
|
1662
1662
|
|
|
1663
|
-
```
|
|
1663
|
+
```typescript
|
|
1664
1664
|
export async function getIPStatus(request, env) {
|
|
1665
1665
|
const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
|
|
1666
1666
|
|
|
@@ -1696,7 +1696,7 @@ export async function getIPStatus(request, env) {
|
|
|
1696
1696
|
|
|
1697
1697
|
### 6.3 Endpoint: `/api/security/audit-logs`
|
|
1698
1698
|
|
|
1699
|
-
```
|
|
1699
|
+
```typescript
|
|
1700
1700
|
export async function getAuditLogs(request, env) {
|
|
1701
1701
|
const url = new URL(request.url);
|
|
1702
1702
|
const filters = {
|
|
@@ -1729,10 +1729,10 @@ export async function getAuditLogs(request, env) {
|
|
|
1729
1729
|
|
|
1730
1730
|
## 🎯 FORMATO DE SAÍDA
|
|
1731
1731
|
|
|
1732
|
-
### DELIVERABLE 1: `security-middleware.
|
|
1732
|
+
### DELIVERABLE 1: `modules/security-middleware.ts`
|
|
1733
1733
|
|
|
1734
|
-
```
|
|
1735
|
-
// security-middleware.
|
|
1734
|
+
```typescript
|
|
1735
|
+
// modules/security-middleware.ts - Middleware de segurança completo
|
|
1736
1736
|
export {
|
|
1737
1737
|
applyRateLimiting,
|
|
1738
1738
|
checkIPBlocking,
|
|
@@ -1765,7 +1765,7 @@ CREATE TABLE IF NOT EXISTS audit_logs (...);
|
|
|
1765
1765
|
|
|
1766
1766
|
### DELIVERABLE 3: `security-config.js`
|
|
1767
1767
|
|
|
1768
|
-
```
|
|
1768
|
+
```typescript
|
|
1769
1769
|
// security-config.js - Configuração de segurança
|
|
1770
1770
|
export const RATE_LIMIT_CONFIG = { ... };
|
|
1771
1771
|
export const IP_BLOCKING_CONFIG = { ... };
|
|
@@ -12,7 +12,7 @@ Ao ser ativado, você sempre gera os seguintes arquivos:
|
|
|
12
12
|
|---|---|
|
|
13
13
|
| `wrangler.toml` | Configuração completa do Worker com todos os bindings |
|
|
14
14
|
| `schema.sql` | Schema D1 completo: eventos, identity_graph, leads, behavioral_events |
|
|
15
|
-
| `
|
|
15
|
+
| `index.ts` | O Worker principal com lógica de processamento e engagement scoring server-side |
|
|
16
16
|
| `DEPLOY.md` | Guia passo a passo de deploy do zero ao funcionando |
|
|
17
17
|
|
|
18
18
|
---
|
|
@@ -56,7 +56,7 @@ Cloudflare Edge (Worker)
|
|
|
56
56
|
|
|
57
57
|
```toml
|
|
58
58
|
name = "cdp-edge-worker"
|
|
59
|
-
main = "
|
|
59
|
+
main = "index.ts"
|
|
60
60
|
compatibility_date = "2025-01-01"
|
|
61
61
|
compatibility_flags = ["nodejs_compat"]
|
|
62
62
|
|
|
@@ -213,7 +213,7 @@ CREATE INDEX IF NOT EXISTS idx_behavioral_events_engagement ON behavioral_events
|
|
|
213
213
|
|
|
214
214
|
## 📄 WORKER.JS (TEMPLATE COMPLETO)
|
|
215
215
|
|
|
216
|
-
```
|
|
216
|
+
```typescript
|
|
217
217
|
/**
|
|
218
218
|
* CDPEDGE CLOUDFLARE WORKER - Quantum Tier
|
|
219
219
|
*/
|
|
@@ -690,7 +690,7 @@ O engagement scoring no servidor é mais preciso que no browser porque tem acess
|
|
|
690
690
|
|
|
691
691
|
### Cálculo por Componente
|
|
692
692
|
|
|
693
|
-
```
|
|
693
|
+
```typescript
|
|
694
694
|
// 1. Visit Score (25%)
|
|
695
695
|
function calculateVisitScore(visitorContext) {
|
|
696
696
|
const visitCount = visitorContext.visit_count || 1;
|
|
@@ -757,7 +757,7 @@ const finalScore = (
|
|
|
757
757
|
### Integração com Plataformas
|
|
758
758
|
|
|
759
759
|
**Meta CAPI v22.0:**
|
|
760
|
-
```
|
|
760
|
+
```typescript
|
|
761
761
|
custom_data: {
|
|
762
762
|
engagement_score: engagementScore.server_engagement_score,
|
|
763
763
|
intention_level: engagementScore.final_intention_level,
|
|
@@ -772,7 +772,7 @@ custom_data: {
|
|
|
772
772
|
```
|
|
773
773
|
|
|
774
774
|
**Google GA4 Measurement Protocol:**
|
|
775
|
-
```
|
|
775
|
+
```typescript
|
|
776
776
|
custom_params: {
|
|
777
777
|
engagement_score: engagementScore.server_engagement_score,
|
|
778
778
|
intention_level: engagementScore.final_intention_level,
|
|
@@ -782,7 +782,7 @@ custom_params: {
|
|
|
782
782
|
```
|
|
783
783
|
|
|
784
784
|
**TikTok Events API v1.3:**
|
|
785
|
-
```
|
|
785
|
+
```typescript
|
|
786
786
|
context: {
|
|
787
787
|
user: {
|
|
788
788
|
engagement_score: engagementScore.server_engagement_score,
|
|
@@ -821,7 +821,7 @@ context: {
|
|
|
821
821
|
- SameSite=Lax para balance entre segurança e funcionalidade
|
|
822
822
|
|
|
823
823
|
**3. Response Headers Anti-Blocking:**
|
|
824
|
-
```
|
|
824
|
+
```typescript
|
|
825
825
|
const corsHeaders = {
|
|
826
826
|
'Access-Control-Allow-Origin': '*',
|
|
827
827
|
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
@@ -883,7 +883,7 @@ Tentativa 3 (Cloudflare Queue - 15 minutos)
|
|
|
883
883
|
|
|
884
884
|
Toda função de dispatch (Meta, Google, TikTok) DEVE ter try/catch com gravação:
|
|
885
885
|
|
|
886
|
-
```
|
|
886
|
+
```typescript
|
|
887
887
|
// Exemplo para dispatchMetaCapi com escalonamento
|
|
888
888
|
async function dispatchMetaCapi(body, env, visitor, heatScore, clientIP, userAgent, cf, retryCount = 0) {
|
|
889
889
|
if (!env.META_ACCESS_TOKEN || !body.pixel_id) {
|
|
@@ -967,7 +967,7 @@ CREATE INDEX IF NOT EXISTS idx_retry_scheduled ON retry_queue(scheduled_at, stat
|
|
|
967
967
|
|
|
968
968
|
### PASSO 3 — Funções de Log de Sucesso/Falha
|
|
969
969
|
|
|
970
|
-
```
|
|
970
|
+
```typescript
|
|
971
971
|
// Log de sucesso
|
|
972
972
|
async function logEventSuccess(DB, platform, eventId) {
|
|
973
973
|
if (!DB) return;
|
|
@@ -1033,7 +1033,7 @@ async function enqueueRetry(queue, retryData) {
|
|
|
1033
1033
|
|
|
1034
1034
|
Após 3 falhas consecutivas, disparar alerta para o administrador:
|
|
1035
1035
|
|
|
1036
|
-
```
|
|
1036
|
+
```typescript
|
|
1037
1037
|
// Função de alerta integrada com WhatsApp Agent
|
|
1038
1038
|
async function dispatchAlert(platform, eventId, errorMessage) {
|
|
1039
1039
|
const alertMessage = `
|
|
@@ -1098,9 +1098,9 @@ max_batch_timeout = 60
|
|
|
1098
1098
|
cron = "* * * * *" # A cada minuto
|
|
1099
1099
|
```
|
|
1100
1100
|
|
|
1101
|
-
E no `
|
|
1101
|
+
E no `index.ts`, adicionar handler de queue:
|
|
1102
1102
|
|
|
1103
|
-
```
|
|
1103
|
+
```typescript
|
|
1104
1104
|
// Handler de Queue (retries)
|
|
1105
1105
|
export async function queue(batch, env) {
|
|
1106
1106
|
for (const message of batch.messages) {
|
|
@@ -1150,7 +1150,7 @@ export async function queue(batch, env) {
|
|
|
1150
1150
|
|
|
1151
1151
|
- Gerar `wrangler.toml` completo com bindings D1, KV, R2, Queues e Cron Triggers
|
|
1152
1152
|
- Gerar `schema.sql` com todas as tabelas: `events_log`, `identity_graph`, `leads`, `behavioral_events`, `webhook_events`, `user_profiles`
|
|
1153
|
-
- Gerar `
|
|
1153
|
+
- Gerar `index.ts` principal com endpoint `/track` (recebe eventos do browser)
|
|
1154
1154
|
- Implementar Identity Graph sync, Engagement Scoring server-side e First-Party Cookie (`_cdp_uid`)
|
|
1155
1155
|
- Implementar Anti-Blocking: CORS same-domain, headers limpos, sem keywords bloqueáveis
|
|
1156
1156
|
- Implementar sistema de retry com Cloudflare Queues (3-Tier: imediato → 5min → 15min → 45min)
|
|
@@ -1163,7 +1163,7 @@ export async function queue(batch, env) {
|
|
|
1163
1163
|
"arquivos_gerados": [
|
|
1164
1164
|
"wrangler.toml",
|
|
1165
1165
|
"schema.sql",
|
|
1166
|
-
"
|
|
1166
|
+
"index.ts",
|
|
1167
1167
|
"DEPLOY.md"
|
|
1168
1168
|
],
|
|
1169
1169
|
"endpoints": {
|
|
@@ -35,7 +35,7 @@ Database: Cloudflare D1 (Persistência)
|
|
|
35
35
|
- Gera `event_id` para deduplicação com server-side
|
|
36
36
|
|
|
37
37
|
### 2. Server Tracking (Spotify Conversions API)
|
|
38
|
-
- `spotify
|
|
38
|
+
- `modules/dispatch/spotify.ts` — Payloads para API de conversões Spotify
|
|
39
39
|
- Envia eventos para Conversions API com deduplicação
|
|
40
40
|
- Usa `crypto.subtle.digest('SHA-256')` para PII (email, phone)
|
|
41
41
|
|
|
@@ -48,7 +48,7 @@ Database: Cloudflare D1 (Persistência)
|
|
|
48
48
|
| Arquivo | Descrição |
|
|
49
49
|
|---------|-----------|
|
|
50
50
|
| `spotify-pixel.js` | Spotify Pixel SDK (Browser) |
|
|
51
|
-
| `spotify
|
|
51
|
+
| `modules/dispatch/spotify.ts` | Spotify Conversions API Payloads (Server — TypeScript) |
|
|
52
52
|
|
|
53
53
|
---
|
|
54
54
|
|
|
@@ -219,12 +219,12 @@ Spotify Ads suporta Advanced Matching para melhorar a qualidade do sinal:
|
|
|
219
219
|
|
|
220
220
|
## 💻 O QUE VOCÊ GERA (SERVER)
|
|
221
221
|
|
|
222
|
-
### `spotify
|
|
222
|
+
### `modules/dispatch/spotify.ts`
|
|
223
223
|
|
|
224
|
-
```
|
|
224
|
+
```typescript
|
|
225
225
|
/**
|
|
226
226
|
* Spotify Conversions API - Server-Side Tracking
|
|
227
|
-
* CDP Edge Quantum Tier - Cloudflare Worker
|
|
227
|
+
* CDP Edge Quantum Tier - Cloudflare Worker (TypeScript)
|
|
228
228
|
*/
|
|
229
229
|
|
|
230
230
|
/**
|
|
@@ -349,7 +349,7 @@ Ao final, gere um relatório JSON:
|
|
|
349
349
|
"fix": "Adicionar comentário explicando integração"
|
|
350
350
|
},
|
|
351
351
|
{
|
|
352
|
-
"file": "spotify
|
|
352
|
+
"file": "modules/dispatch/spotify.ts",
|
|
353
353
|
"issue": "Descrição",
|
|
354
354
|
"fix": "Adicionar retry logic com Promise.allSettled"
|
|
355
355
|
}
|
|
@@ -23,7 +23,7 @@ Especialista exclusivo em TikTok Pixel (browser via cdpTrack) + TikTok Events AP
|
|
|
23
23
|
|
|
24
24
|
### PASSO 0 — Ler Versões Atuais
|
|
25
25
|
|
|
26
|
-
```
|
|
26
|
+
```typescript
|
|
27
27
|
// Ler versões do arquivo centralizado
|
|
28
28
|
const apiVersions = await readJSON('contracts/api-versions.json');
|
|
29
29
|
const tiktokVersion = apiVersions.tiktok;
|
|
@@ -85,7 +85,7 @@ Conforme `contracts/api-versions.json`, a TikTok Events API tem limites estritos
|
|
|
85
85
|
|
|
86
86
|
### Implementação de Throttling no Worker
|
|
87
87
|
|
|
88
|
-
```
|
|
88
|
+
```typescript
|
|
89
89
|
// Rate limit KV key: 'tiktok_rate_{pixel_id}_{minute}'
|
|
90
90
|
async function dispatchTikTokWithRateLimit(env, events, pixelId, accessToken) {
|
|
91
91
|
const now = new Date();
|
|
@@ -161,7 +161,7 @@ async function dispatchTikTokWithRateLimit(env, events, pixelId, accessToken) {
|
|
|
161
161
|
{
|
|
162
162
|
"arquivos_gerados": {
|
|
163
163
|
"browser": "cdpTrack.js (eventos TikTok injetados)",
|
|
164
|
-
"server": "
|
|
164
|
+
"server": "modules/dispatch/tiktok.ts"
|
|
165
165
|
},
|
|
166
166
|
"versao_api": "v1.3",
|
|
167
167
|
"endpoint": "/open_api/v1.3/event/track/",
|
|
@@ -28,7 +28,7 @@ Gerar um tracking plan **validado e verificável** que elimine:
|
|
|
28
28
|
|
|
29
29
|
### 1.1 Verificar Cobertura de Eventos
|
|
30
30
|
|
|
31
|
-
```
|
|
31
|
+
```typescript
|
|
32
32
|
// Comparar eventos do Page Analyzer com outputs dos agentes
|
|
33
33
|
function validateEventCoverage(pageAnalysis, agentOutputs) {
|
|
34
34
|
const pageEvents = new Set();
|
|
@@ -89,7 +89,7 @@ function validateEventCoverage(pageAnalysis, agentOutputs) {
|
|
|
89
89
|
|
|
90
90
|
### 1.2 Verificar Consistência de Parâmetros
|
|
91
91
|
|
|
92
|
-
```
|
|
92
|
+
```typescript
|
|
93
93
|
// Verificar se eventos de conversão têm todos os campos críticos
|
|
94
94
|
function validateConversionParameters(events, apiVersions) {
|
|
95
95
|
const criticalFields = ['value', 'currency', 'content_ids', 'transaction_id'];
|
|
@@ -118,7 +118,7 @@ function validateConversionParameters(events, apiVersions) {
|
|
|
118
118
|
|
|
119
119
|
### 1.3 Verificar Seletores Implementados
|
|
120
120
|
|
|
121
|
-
```
|
|
121
|
+
```typescript
|
|
122
122
|
// Verificar se seletores no tracking plan existem no código
|
|
123
123
|
function validateSelectorsExist(trackingPlan, pageAnalysis) {
|
|
124
124
|
const missingSelectors = [];
|
|
@@ -158,7 +158,7 @@ function validateSelectorsExist(trackingPlan, pageAnalysis) {
|
|
|
158
158
|
|
|
159
159
|
### 1.4 Verificar Versões de API
|
|
160
160
|
|
|
161
|
-
```
|
|
161
|
+
```typescript
|
|
162
162
|
// Ler api-versions.json e verificar consistência
|
|
163
163
|
async function validateApiVersions(trackingPlan) {
|
|
164
164
|
const apiVersions = await readJSON('contracts/api-versions.json');
|
|
@@ -200,7 +200,7 @@ async function validateApiVersions(trackingPlan) {
|
|
|
200
200
|
|
|
201
201
|
### 1.5 Validação Cruzada Completa (runFullValidation)
|
|
202
202
|
|
|
203
|
-
```
|
|
203
|
+
```typescript
|
|
204
204
|
/**
|
|
205
205
|
* Ponto de entrada principal — executa TODAS as validações em sequência
|
|
206
206
|
* e retorna um relatório consolidado com status PASS | WARN | BLOCK
|
|
@@ -78,7 +78,7 @@ Quando detectar erro, emitir bloco `CORRECTION_ROUTE` com formato:
|
|
|
78
78
|
"test_url": "https://graph.facebook.com/v22.0/{PIXEL_ID}/events",
|
|
79
79
|
"response_expected": "200 OK com payload válido"
|
|
80
80
|
},
|
|
81
|
-
"files_affected": ["
|
|
81
|
+
"files_affected": ["index.ts", "modules/dispatch/meta.ts"],
|
|
82
82
|
"auto_fix_available": true,
|
|
83
83
|
"user_action_required": false
|
|
84
84
|
},
|
|
@@ -95,7 +95,7 @@ Quando detectar erro, emitir bloco `CORRECTION_ROUTE` com formato:
|
|
|
95
95
|
"fallback": "gerar novo UUID se não existir",
|
|
96
96
|
"required_for_events": ["purchase", "initiate_checkout"]
|
|
97
97
|
},
|
|
98
|
-
"files_affected": ["ga4
|
|
98
|
+
"files_affected": ["modules/dispatch/ga4.ts", "index.ts"],
|
|
99
99
|
"auto_fix_available": false,
|
|
100
100
|
"user_action_required": true,
|
|
101
101
|
"user_instruction": "Verificar se o D1 está persistindo corretamente o ga_client_id nos cookies do visitante"
|
|
@@ -123,7 +123,7 @@ Para correções com `auto_fix_available: true`, o Validator Agent DEVE:
|
|
|
123
123
|
|
|
124
124
|
#### PASSO 1 — Executar Fix Automático
|
|
125
125
|
|
|
126
|
-
```
|
|
126
|
+
```typescript
|
|
127
127
|
// Exemplo: correção automática de versão de API
|
|
128
128
|
async function applyAutoFix(correction) {
|
|
129
129
|
const { files_affected, check_pattern, expected_pattern } = correction;
|
|
@@ -142,7 +142,7 @@ async function applyAutoFix(correction) {
|
|
|
142
142
|
|
|
143
143
|
#### PASSO 2 — Re-validar após Fix
|
|
144
144
|
|
|
145
|
-
```
|
|
145
|
+
```typescript
|
|
146
146
|
// Após aplicar fix, re-executar validação específica
|
|
147
147
|
async function reValidateAfterFix(correction) {
|
|
148
148
|
const { validation_criteria, files_affected } = correction;
|
|
@@ -171,14 +171,14 @@ Para correções com `user_action_required: true`, emitir instrução estruturad
|
|
|
171
171
|
|
|
172
172
|
**Agente Responsável:** meta-agent
|
|
173
173
|
**Prioridade:** 🔴 CRÍTICO
|
|
174
|
-
**Arquivos Afetados:**
|
|
174
|
+
**Arquivos Afetados:** index.ts, modules/dispatch/meta.ts
|
|
175
175
|
|
|
176
176
|
### Problema Detectado:
|
|
177
177
|
Meta CAPI está usando versão v21.0 (desatualizada) — isso causará rejeição de eventos pela Meta.
|
|
178
178
|
|
|
179
179
|
### O que precisa ser feito:
|
|
180
180
|
|
|
181
|
-
1. **Abrir o arquivo:** `
|
|
181
|
+
1. **Abrir o arquivo:** `modules/dispatch/meta.ts`
|
|
182
182
|
2. **Localizar:** Todas as ocorrências de `/v21.0/`
|
|
183
183
|
3. **Substituir por:** `/v22.0/`
|
|
184
184
|
4. **Testar:** Fazer uma requisição de teste para https://graph.facebook.com/v22.0/{SEU_PIXEL_ID}/events
|
|
@@ -201,7 +201,7 @@ Após cada correção (auto ou manual), o Validator Agent DEVE executar validaç
|
|
|
201
201
|
|
|
202
202
|
#### Para Correções de API Version:
|
|
203
203
|
|
|
204
|
-
```
|
|
204
|
+
```typescript
|
|
205
205
|
{
|
|
206
206
|
"revalidation_checklist": {
|
|
207
207
|
"version_correct": true, // Check: endpoint usa versão correta
|
|
@@ -214,7 +214,7 @@ Após cada correção (auto ou manual), o Validator Agent DEVE executar validaç
|
|
|
214
214
|
|
|
215
215
|
#### Para Correções de Missing Fields:
|
|
216
216
|
|
|
217
|
-
```
|
|
217
|
+
```typescript
|
|
218
218
|
{
|
|
219
219
|
"revalidation_checklist": {
|
|
220
220
|
"field_present": true, // Check: campo existe no payload
|
|
@@ -227,7 +227,7 @@ Após cada correção (auto ou manual), o Validator Agent DEVE executar validaç
|
|
|
227
227
|
|
|
228
228
|
#### Para Correções de Seletores:
|
|
229
229
|
|
|
230
|
-
```
|
|
230
|
+
```typescript
|
|
231
231
|
{
|
|
232
232
|
"revalidation_checklist": {
|
|
233
233
|
"selector_exists": true, // Check: seletor encontrado no HTML/JS
|
|
@@ -16,7 +16,7 @@ Você é o especialista em Webhooks do CDP Edge. Sua missão é capturar vendas
|
|
|
16
16
|
|
|
17
17
|
Antes de qualquer dispatch para CAPI, normalizar e hashear PII extraída do webhook:
|
|
18
18
|
|
|
19
|
-
```
|
|
19
|
+
```typescript
|
|
20
20
|
// Hashing SHA-256 para PII — usar WebCrypto (disponível em Cloudflare Workers)
|
|
21
21
|
async function hashPII(value) {
|
|
22
22
|
if (!value) return null;
|
|
@@ -99,7 +99,7 @@ Webhook (Hotmart/Kiwify/Ticto/Stripe)
|
|
|
99
99
|
|
|
100
100
|
### Código de Integração (webhook handler)
|
|
101
101
|
|
|
102
|
-
```
|
|
102
|
+
```typescript
|
|
103
103
|
// No handler de webhook, após validação e dedup:
|
|
104
104
|
ctx.waitUntil(Promise.allSettled([
|
|
105
105
|
// [5] CAPI dispatch
|
|
@@ -124,8 +124,8 @@ ctx.waitUntil(Promise.allSettled([
|
|
|
124
124
|
]));
|
|
125
125
|
```
|
|
126
126
|
|
|
127
|
-
> **Nota:** `sendEmail()` é implementada pelo Email Agent em `
|
|
128
|
-
> `syncToCRM()` é implementada pelo CRM Integration Agent em `
|
|
127
|
+
> **Nota:** `sendEmail()` é implementada pelo Email Agent em `modules/email-service.ts`.
|
|
128
|
+
> `syncToCRM()` é implementada pelo CRM Integration Agent em `modules/crm-service.ts`.
|
|
129
129
|
|
|
130
130
|
---
|
|
131
131
|
|
|
@@ -66,7 +66,7 @@ WhatsApp Agent dispara notificação ao dono via Meta Cloud API v22.0
|
|
|
66
66
|
|
|
67
67
|
### O que este agente gera para o fluxo CTWA
|
|
68
68
|
|
|
69
|
-
```
|
|
69
|
+
```typescript
|
|
70
70
|
// sendWhatsApp() — notificação ao dono quando chega lead CTWA
|
|
71
71
|
async function notifyOwnerNewCtwaLead(env, contactData) {
|
|
72
72
|
const message = `📲 Novo Lead CTWA!\n\nNome: ${contactData.name || 'Desconhecido'}\nTelefone: ${contactData.phone}\nAnúncio: ${contactData.headline || '-'}\nMensagem: "${contactData.messageBody?.slice(0, 80) || '-'}"`;
|
|
@@ -183,7 +183,7 @@ message_body | Olá, vi o anúncio e tenho interesse
|
|
|
183
183
|
3. `META_APP_SECRET`
|
|
184
184
|
|
|
185
185
|
**O agente gera/descobre o restante automaticamente:**
|
|
186
|
-
```
|
|
186
|
+
```typescript
|
|
187
187
|
// WA_WEBHOOK_VERIFY_TOKEN — gerado pelo agente antes de registrar o webhook
|
|
188
188
|
const WA_WEBHOOK_VERIFY_TOKEN = crypto.randomUUID().replace(/-/g, '') + crypto.randomUUID().replace(/-/g, '');
|
|
189
189
|
// Exemplo: "a3f8c1d2e4b5a6f7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1"
|
|
@@ -504,7 +504,7 @@ echo "{META_APP_SECRET}" | wrangler secret put META_APP_SECRET
|
|
|
504
504
|
echo "{META_ACCESS_TOKEN}" | wrangler secret put META_ACCESS_TOKEN
|
|
505
505
|
|
|
506
506
|
# ── Secrets para Auto-Resposta WhatsApp (enviar mensagens de saída) ─────────
|
|
507
|
-
# Necessários para:
|
|
507
|
+
# Necessários para: index.ts → auto-resposta após Lead/Purchase
|
|
508
508
|
# WHATSAPP_ACCESS_TOKEN = mesmo token Meta (Cloud API) — pode reutilizar META_ACCESS_TOKEN
|
|
509
509
|
# WHATSAPP_PHONE_NUMBER_ID = mesmo {PHONE_ID} descoberto acima
|
|
510
510
|
echo "{META_ACCESS_TOKEN}" | wrangler secret put WHATSAPP_ACCESS_TOKEN
|
|
@@ -682,7 +682,7 @@ PRÓXIMO PASSO:
|
|
|
682
682
|
|
|
683
683
|
| Arquivo | Função |
|
|
684
684
|
|---------|--------|
|
|
685
|
-
| `server-edge-tracker/
|
|
685
|
+
| `server-edge-tracker/index.ts` | `processWhatsAppWebhook()` + rotas `GET/POST /webhook/whatsapp` |
|
|
686
686
|
| `server-edge-tracker/migrate-v6.sql` | Criação da tabela `whatsapp_contacts` com índices |
|
|
687
687
|
| `server-edge-tracker/wrangler.toml` | Configuração do worker + lista de secrets documentados |
|
|
688
688
|
| `docs/whatsapp-ctwa.md` | Documentação técnica completa do módulo CTWA |
|
|
@@ -33,7 +33,7 @@ YouTube Ad (TrueView / Bumper / Non-skip)
|
|
|
33
33
|
|
|
34
34
|
### PASSO 0 — Ler Versões Atuais
|
|
35
35
|
|
|
36
|
-
```
|
|
36
|
+
```typescript
|
|
37
37
|
const apiVersions = await readJSON('contracts/api-versions.json');
|
|
38
38
|
const googleVersions = apiVersions.google;
|
|
39
39
|
|
|
@@ -253,7 +253,7 @@ cdpTrack.updateConsent({ analytics: true, ads: true });
|
|
|
253
253
|
|
|
254
254
|
---
|
|
255
255
|
|
|
256
|
-
## 🛠️ IMPLEMENTAÇÃO SERVER —
|
|
256
|
+
## 🛠️ IMPLEMENTAÇÃO SERVER — index.ts
|
|
257
257
|
|
|
258
258
|
### 1. Extrair e persistir Click IDs do YouTube
|
|
259
259
|
|
|
@@ -262,7 +262,7 @@ O `upsertProfile()` já persiste `gclid`, `wbraid`, `gbraid` no D1.
|
|
|
262
262
|
|
|
263
263
|
Para verificar persistência correta:
|
|
264
264
|
|
|
265
|
-
```
|
|
265
|
+
```typescript
|
|
266
266
|
// D1: user_profiles — colunas já existentes
|
|
267
267
|
// gclid TEXT — Google Ads standard click ID
|
|
268
268
|
// wbraid TEXT — iOS privacy-preserving (YouTube)
|
|
@@ -271,7 +271,7 @@ Para verificar persistência correta:
|
|
|
271
271
|
|
|
272
272
|
### 2. GA4 Measurement Protocol — Eventos de Vídeo
|
|
273
273
|
|
|
274
|
-
```
|
|
274
|
+
```typescript
|
|
275
275
|
// No sendGA4Mp() — adicionar mapeamento de eventos YouTube
|
|
276
276
|
const VIDEO_GA4_MAP = {
|
|
277
277
|
video_start: 'video_start',
|
|
@@ -293,7 +293,7 @@ const videoParams = {
|
|
|
293
293
|
|
|
294
294
|
### 3. Google Ads Enhanced Conversions — Lead de Vídeo
|
|
295
295
|
|
|
296
|
-
```
|
|
296
|
+
```typescript
|
|
297
297
|
// Conversão de Lead gerada por campanha YouTube
|
|
298
298
|
// Envia para GA4 MP com user_data para Enhanced Conversions
|
|
299
299
|
const enhancedConversionPayload = {
|
|
@@ -326,7 +326,7 @@ const enhancedConversionPayload = {
|
|
|
326
326
|
Para campanhas Bumper/Non-skip, o usuário converte DEPOIS sem clicar.
|
|
327
327
|
O Worker detecta isso quando um Lead chega SEM gclid mas com histórico de impressão YouTube:
|
|
328
328
|
|
|
329
|
-
```
|
|
329
|
+
```typescript
|
|
330
330
|
// No upsertProfile() — verificar se perfil tem impressão YouTube recente
|
|
331
331
|
// (requer webhook do Google Ads — avançado, Fase 5)
|
|
332
332
|
// Por ora: registrar ausência de gclid + utm_source=youtube como view-through candidate
|
|
@@ -418,7 +418,7 @@ const YOUTUBE_AUDIENCES_IMOVEIS = {
|
|
|
418
418
|
|
|
419
419
|
### Customer Match — Exportar leads do D1 para Google Ads
|
|
420
420
|
|
|
421
|
-
```
|
|
421
|
+
```typescript
|
|
422
422
|
// Endpoint no Worker: GET /export/customer-match
|
|
423
423
|
// Gera CSV criptografado para upload no Google Ads
|
|
424
424
|
|
|
@@ -449,7 +449,7 @@ async function exportCustomerMatchList(env) {
|
|
|
449
449
|
|
|
450
450
|
O Intelligence Agent (cron semanal) deve incluir check de YouTube:
|
|
451
451
|
|
|
452
|
-
```
|
|
452
|
+
```typescript
|
|
453
453
|
// Adicionar ao checkApiVersionsIntelligence():
|
|
454
454
|
// Verificar se wbraid/gbraid estão chegando nos leads
|
|
455
455
|
// (indica que campanhas YouTube iOS estão funcionando)
|
|
@@ -518,7 +518,7 @@ if (youtubeMobileLeads.count === 0) {
|
|
|
518
518
|
{
|
|
519
519
|
"arquivos_gerados": {
|
|
520
520
|
"browser": "cdpTrack.js (eventos YouTube + IFrame API listener)",
|
|
521
|
-
"server": "
|
|
521
|
+
"server": "modules/dispatch/ga4.ts (já inclui YouTube via GA4)"
|
|
522
522
|
},
|
|
523
523
|
"eventos_implementados": [
|
|
524
524
|
"video_start",
|
|
@@ -552,16 +552,6 @@ export function setupAutoFormCapture() {
|
|
|
552
552
|
}, true); // Capture para formulários dinâmicos
|
|
553
553
|
}
|
|
554
554
|
|
|
555
|
-
/**
|
|
556
|
-
* trackPurchase() — Captura de compra
|
|
557
|
-
*
|
|
558
|
-
* @param {object} orderData - Dados da compra (order_id, value, currency, etc.)
|
|
559
|
-
* @returns {Promise} - Promise com resultado
|
|
560
|
-
*/
|
|
561
|
-
export async function trackPurchase(orderData) {
|
|
562
|
-
return track('Purchase', orderData);
|
|
563
|
-
}
|
|
564
|
-
|
|
565
555
|
/**
|
|
566
556
|
* trackViewContent() — Captura de visualização de conteúdo
|
|
567
557
|
*
|
|
@@ -21,8 +21,8 @@ const ENGAGEMENT_CONFIG = {
|
|
|
21
21
|
clickWeights: {
|
|
22
22
|
'generico': 1.0, // clique sem categoria
|
|
23
23
|
'cta': 2.5, // clique em CTA
|
|
24
|
-
'button': 2.0
|
|
25
|
-
'link': 1.5
|
|
24
|
+
'button': 2.0, // clique em botão
|
|
25
|
+
'link': 1.5, // clique em link
|
|
26
26
|
'input': 0.5, // clique em input
|
|
27
27
|
},
|
|
28
28
|
videoWeights: {
|