cdp-edge 1.12.0 → 1.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 CHANGED
@@ -7,15 +7,15 @@
7
7
  - **Precisão Máxima**: Meta CAPI v22.0+, GA4 MP e TikTok Events API v1.3.
8
8
  - **Identity Graph**: Persistência de leads e eventos via Cloudflare D1.
9
9
  - **Anti-Adblock**: Endpoint Same-Domain indetectável.
10
- - **Human-Behavior Engine**: Score de engajamento (0-100) em tempo real.
10
+ - **Human-Behavior Engine**: Score de engajamento em tempo real.
11
11
  - **Queue Retry**: Zero perda de conversão — eventos com falha reenfileirados automaticamente.
12
- - **Geo Intelligence**: Cidade, estado e CEP em todos os eventos (Workers Paid).
12
+ - **Geo Intelligence**: Cidade, estado e CEP em todos os eventos.
13
13
 
14
14
  ---
15
15
 
16
- ## 🏗️ ARQUITETURA QUANTUM (CLOUDFARE NATIVE)
16
+ ## 🏗️ ARQUITETURA QUANTUM (CLOUDFLARE NATIVE)
17
17
 
18
- O CDP Edge não é um "script de rastreio", é uma **Content Delivery Network (CDN)** com inteligência de dados acoplada.
18
+ O CDP Edge não é um "script de rastreio", é uma **infraestrutura de borda** com inteligência de dados acoplada.
19
19
 
20
20
  ```mermaid
21
21
  graph TD
@@ -33,168 +33,106 @@ graph TD
33
33
 
34
34
  ## 🖱 CATÁLOGO DE AGENTES ESPECIALISTAS
35
35
 
36
- O sistema é composto por mais de 30 agentes coordenados pelo **Master Orchestrator**. Cada um possui uma função técnica específica:
36
+ O sistema é composto por **39+ agentes** coordenados pelo **Master Orchestrator**:
37
37
 
38
38
  ### 🧠 Núcleo de Inteligência
39
39
  | Agente | Função |
40
40
  |---|---|
41
- | **Master Orchestrator** | Coordenação central de especialistas e validação Quantum Tier. |
42
- | **Page Analyzer** | Mapeamento automático de CTAs, Forms e Nicho do site. |
43
- | **Validator Agent** | Auditoria de código, segurança e conformidade de APIs. |
44
- | **Memory Agent** | Gestão de contexto e checkpoints técnicos da sessão. |
45
- | **Intelligence Agent** | Monitoramento de atualizações de API (Meta v22.0+, etc). |
41
+ | **Master Orchestrator** | Coordenação central guia todo o setup do projeto |
42
+ | **Page Analyzer** | Mapeamento automático de CTAs, Forms e nicho do site |
43
+ | **Validator Agent** | Auditoria de código, segurança e conformidade de APIs |
44
+ | **Memory Agent** | Contexto e checkpoints da sessão por projeto |
45
+ | **Intelligence Agent** | Monitoramento de versões de API (Meta v22.0+, etc) |
46
46
 
47
- ### 🚀 Despachantes de Plataforma
47
+ ### 🚀 Plataformas de Anúncio
48
48
  | Agente | Especialidade |
49
49
  |---|---|
50
- | **Meta Agent** | Facebook Pixel + CAPI (EMQ Max). |
51
- | **Google Agent** | GA4 + Google Ads Server-Side. |
52
- | **TikTok Agent** | TikTok Pixel + Events API v1.3. |
53
- | **Plataformas Ads** | Pinterest, Reddit, Bing, LinkedIn, Spotify. |
54
- | **Browser Agent** | Geração do SDK `cdpTrack.js` lightweight. |
55
-
56
- ### 🛡️ Módulos Enterprise (Premium)
50
+ | **Meta Agent** | Facebook Pixel + CAPI v22.0 + WhatsApp CTWA |
51
+ | **Google Agent** | GA4 + Google Ads Enhanced Conversions |
52
+ | **TikTok Agent** | TikTok Pixel + Events API v1.3 |
53
+ | **LinkedIn Agent** | Insight Tag + Conversions API v2 |
54
+ | **Pinterest Agent** | Tag + Conversions API v5 |
55
+ | **Reddit Agent** | Pixel + Conversions API v2.0 |
56
+ | **Spotify Agent** | Pixel + Conversions API v1 |
57
+ | **Bing Agent** | UET Tag + Enhanced Conversions |
58
+
59
+ ### 🛡️ Módulos Enterprise
57
60
  | Agente | Função |
58
61
  |---|---|
59
- | **Attribution Agent** | Atribuição Multi-Touch de alta fidelidade. |
60
- | **Security Agent** | Rate Limiting, Criptografia AES-256 e Bot Defense. |
61
- | **Compliance Agent** | Gestão de LGPD e GDPR (Consent Mode v2). |
62
- | **Performance Opt.** | Otimização de Caches e Queries D1 SQL. |
63
- | **CRM Integration** | Sincronia D1 ↔ HubSpot/Salesforce via CRM Agent. |
62
+ | **Attribution Agent** | Atribuição Multi-Touch de alta fidelidade |
63
+ | **Security Agent** | Rate Limiting, AES-256 e Bot Defense |
64
+ | **Compliance Agent** | LGPD e GDPR (Consent Mode v2) |
65
+ | **Performance Agent** | Otimização de caches e queries D1 |
66
+ | **CRM Integration** | Sincronia D1 ↔ HubSpot/Salesforce |
64
67
 
65
68
  ---
66
69
 
67
70
  ## 💻 INSTALAÇÃO E USO
68
71
 
69
- ### Instalar Globalmente
70
-
71
- ```bash
72
- npm install -g cdp-edge
73
- cdp-edge --version
74
- ```
72
+ > ⚠️ **Importante:** Execute **um comando por vez** e aguarde terminar antes de rodar o próximo.
75
73
 
76
74
  ---
77
75
 
78
- ## 📋 COMANDOS DISPONÍVEIS
79
-
80
- ### `install` — Instalar CDP Edge em um projeto cliente
81
-
82
- **O comando principal.** Configura o CDP Edge em qualquer projeto e habilita o `/cdp` no Claude Code.
76
+ ### Passo 1 — Instalar o CLI globalmente
83
77
 
84
78
  ```bash
85
- # Instalar no diretório atual
86
- cdp-edge install .
87
-
88
- # Instalar em outro diretório
89
- cdp-edge install ./meu-projeto
90
-
91
- # Com nome do projeto
92
- cdp-edge install ./meu-projeto --name "Landing Page XYZ"
93
-
94
- # Incluir .cursorrules para Cursor IDE
95
- cdp-edge install ./meu-projeto --cursor
79
+ npm install -g cdp-edge
96
80
  ```
97
81
 
98
- **O que cria na raiz do projeto:**
99
-
100
- | Arquivo/Pasta | Função |
101
- |---|---|
102
- | `cdp-edge/` | Skill completa (agentes, SDK, worker, templates, docs) |
103
- | `.claude/commands/cdp.md` | Habilita `/cdp` no Claude Code |
104
- | `CLAUDE.md` | Auto-ativação ao abrir sessão |
105
- | `.cursorrules` | Integração Cursor IDE (flag `--cursor`) |
106
-
107
- **Fluxo após install:**
82
+ Verifique a instalação:
108
83
 
109
84
  ```bash
110
- # 1. Criar e instalar
111
- mkdir meu-projeto
112
- cdp-edge install ./meu-projeto
113
-
114
- # 2. Abrir no Claude Code
115
- claude ./meu-projeto
116
-
117
- # 3. Ativar o Orchestrator
118
- /cdp
85
+ cdp-edge --version
119
86
  ```
120
87
 
121
88
  ---
122
89
 
123
- ### Outros Comandos
90
+ ### Passo 2 — Criar a pasta do projeto e instalar o CDP Edge
124
91
 
125
- #### `setup` Wizard interativo
92
+ Crie a pasta do projeto, abra o terminal dentro dela e execute:
126
93
 
127
94
  ```bash
128
- cdp-edge setup
129
- cdp-edge setup ./meu-projeto
95
+ cdp-edge install . --name "Nome do Projeto"
130
96
  ```
131
97
 
132
- **O que faz:**
133
- - Pergunta plataformas (Meta, TikTok, GA4, etc.)
134
- - Pergunta tipo de produto (lead, checkout, webinar, etc.)
135
- - Gera código de tracking (Browser + Server)
136
- - Cria schema D1 SQL e configuração Wrangler
98
+ **O que é criado na pasta:**
137
99
 
138
- ---
139
-
140
- #### `analyze`Analisar páginas
141
-
142
- ```bash
143
- cdp-edge analyze .
144
- cdp-edge analyze ./meu-projeto
145
- ```
146
-
147
- **O que faz:**
148
- - Detecta CTAs e formulários
149
- - Identifica nicho do negócio
150
- - Sugere micro-eventos comportamentais
100
+ | Arquivo/Pasta | Função |
101
+ |---|---|
102
+ | `cdp-edge/` | Skill completa 39+ agentes, SDK, worker, templates, docs |
103
+ | `.claude/commands/cdp.md` | Habilita o comando `/cdp` no Claude Code |
104
+ | `CLAUDE.md` | Auto-ativação do Orchestrator ao abrir sessão |
151
105
 
152
106
  ---
153
107
 
154
- #### `server`Gerar infraestrutura Cloudflare
108
+ ### Passo 4 Abrir no Claude Code e ativar
155
109
 
156
110
  ```bash
157
- cdp-edge server .
158
- cdp-edge server ./meu-worker
111
+ claude .
159
112
  ```
160
113
 
161
- **Arquivos gerados:**
162
- - `worker.js` — Cloudflare Worker completo
163
- - `schema.sql` — Schema D1
164
- - `wrangler.toml` — Configuração Wrangler
114
+ Dentro do Claude Code, digite:
165
115
 
166
- ---
167
-
168
- #### `validate` — Auditar tracking existente
169
-
170
- ```bash
171
- cdp-edge validate tracking.js
172
116
  ```
173
-
174
- **O que verifica:**
175
- - `event_id` para deduplicação
176
- - SHA256 para PII (e-mail, telefone)
177
- - Detecção de GTM/Stape
178
- - Conformidade com APIs
179
-
180
- ---
181
-
182
- #### `infra` — Guia de infraestrutura Cloudflare
183
-
184
- ```bash
185
- cdp-edge infra
117
+ /cdp
186
118
  ```
187
119
 
120
+ O **Master Orchestrator** inicia e guia todo o setup — plataformas, credenciais e geração da infraestrutura.
121
+
188
122
  ---
189
123
 
190
- ## 🔄 CICLO DE VIDA DO SETUP (/setup)
124
+ ## 📋 COMANDOS DISPONÍVEIS
191
125
 
192
- 1. **FASE 0 Checkpoint:** Sincronização de contexto via Memory Agent.
193
- 2. **FASE 1 — Análise:** Detecção automática de nicho e estrutura da página.
194
- 3. **FASE 2 Mapeamento:** Identificação de CTAs, Forms e Gateways de venda.
195
- 4. **FASE 3 Geração:** Código paralelo para Browser (`cdpTrack`), Worker e D1 SQL.
196
- 5. **FASE 4 Auditoria:** Validação rigorosa e correções automáticas (Validator).
197
- 6. **FASE 5 Deploy:** Publicação instantânea via `wrangler deploy`.
126
+ | Comando | Descrição |
127
+ |---------|-----------|
128
+ | `cdp-edge install [dir]` | **Instala CDP Edge no projeto + habilita /cdp** |
129
+ | `cdp-edge setup [dir]` | Wizard interativo de configuração |
130
+ | `cdp-edge analyze <dir>` | Analisa páginas e detecta eventos |
131
+ | `cdp-edge server <dir>` | Gera infraestrutura Cloudflare Workers + D1 |
132
+ | `cdp-edge validate <file>` | Audita tracking existente |
133
+ | `cdp-edge infra` | Guia de setup de infraestrutura Cloudflare |
134
+ | `cdp-edge --version` | Versão instalada |
135
+ | `cdp-edge --help` | Ajuda completa |
198
136
 
199
137
  ---
200
138
 
@@ -202,25 +140,23 @@ cdp-edge infra
202
140
 
203
141
  ```text
204
142
  CDP Edge/
205
- ├── README.md # Você está aqui.
206
- ├── CLAUDE.md # Guia de desenvolvimento e padrões.
207
- ├── extracted-skill/ # O motor da IA (Agentes e Knowledge Base).
143
+ ├── README.md
144
+ ├── CLAUDE.md # Guia de desenvolvimento e padrões
145
+ ├── extracted-skill/
208
146
  │ └── tracking-events-generator/
209
147
  │ ├── agents/ # 39+ agentes especialistas
210
148
  │ ├── cdpTrack.js # SDK Browser (window.cdpTrack)
211
149
  │ └── micro-events.js # Scroll, vídeo, hover, click tracking
212
- ├── server-edge-tracker/ # Cloudflare Worker (Infra de Borda)
213
- │ ├── worker.js # Handler principal + Queue consumer
150
+ ├── server-edge-tracker/
151
+ │ ├── worker.js # Cloudflare Worker principal
214
152
  │ ├── schema.sql # D1 Schema (Identity Graph)
215
153
  │ └── wrangler.toml # Bindings: D1 + Queue + KV + AI
216
- ├── bin/ # CLI Executável (cdp-edge)
154
+ ├── bin/ # CLI Executável
217
155
  ├── dist/commands/ # Implementação dos comandos CLI
218
- │ └── install.js # cdp-edge install
219
156
  ├── templates/
220
157
  │ ├── install/
221
158
  │ │ ├── CLAUDE.md # Template de auto-ativação para projetos
222
- │ │ └── .claude/commands/
223
- │ │ └── cdp.md # Define /cdp no Claude Code
159
+ │ │ └── .claude/commands/cdp.md # Define /cdp no Claude Code
224
160
  │ ├── vsl-page.md # Template VSL / vídeo de vendas
225
161
  │ └── afiliado-sem-landing.md # Template bridge page afiliado
226
162
  └── docs/
@@ -234,128 +170,108 @@ CDP Edge/
234
170
 
235
171
  ## 📚 EXEMPLOS DE USO
236
172
 
237
- ### Cenário 1: Novo projeto com Claude Code
173
+ ### Novo projeto com Claude Code
238
174
 
239
175
  ```bash
240
- # 1. Criar projeto e instalar CDP Edge
241
- mkdir landing-page-lead
242
- cdp-edge install ./landing-page-lead --name "Landing Page Lead"
176
+ # 1. Crie a pasta do projeto e abra o terminal dentro dela
243
177
 
244
- # 2. Abrir no Claude Code
245
- claude ./landing-page-lead
178
+ # 2. Instalar CDP Edge
179
+ cdp-edge install . --name "Landing Page Lead"
246
180
 
247
- # 3. Ativar o Orchestrator
181
+ # 3. Abrir no Claude Code
182
+ claude .
183
+
184
+ # 4. Ativar o Orchestrator
248
185
  /cdp
249
- # → CDP Edge inicia, faz perguntas, gera toda a infraestrutura
250
186
  ```
251
187
 
252
- ### Cenário 2: Apenas Infraestrutura Cloudflare
188
+ ### Gerar apenas infraestrutura Cloudflare
253
189
 
254
190
  ```bash
255
- # 1. Gerar infraestrutura Worker + D1
256
191
  cdp-edge server ./meu-worker
257
-
258
- # 2. Deploy
259
192
  cd meu-worker
260
193
  wrangler deploy
261
-
262
- # 3. Configurar secrets
263
- wrangler secret put META_ACCESS_TOKEN
264
- wrangler secret put TIKTOK_ACCESS_TOKEN
265
194
  ```
266
195
 
267
- ### Cenário 3: Validar Código Existente
196
+ ### Validar tracking existente
268
197
 
269
198
  ```bash
270
199
  cdp-edge validate tracking.js
271
-
272
- # Status: PASS | Score: 85/100
273
- # ⚠ Hashing não detectado para PII
274
200
  ```
275
201
 
276
- ### Cenário 4: Análise de Projeto
202
+ ### Analisar projeto
277
203
 
278
204
  ```bash
279
- cdp-edge analyze ./meu-projeto-web
280
-
281
- # 📊 Eventos detectados: leads: 2 | purchases: 1 | views: 3
282
- # 🎯 Nicho identificado: E-commerce
205
+ cdp-edge analyze ./meu-projeto
283
206
  ```
284
207
 
285
208
  ---
286
209
 
287
- ## COMANDOS RÁPIDOS (CLI)
210
+ ## 🔧 SOLUÇÃO DE PROBLEMAS
288
211
 
289
- | Comando | Descrição |
290
- |---------|-----------|
291
- | `cdp-edge install [dir]` | **Instala CDP Edge + habilita /cdp no Claude Code** |
292
- | `cdp-edge setup [dir]` | Configuração guiada (wizard) |
293
- | `cdp-edge analyze <dir>` | Análise de páginas |
294
- | `cdp-edge server <dir>` | Gerar infraestrutura Workers + D1 |
295
- | `cdp-edge validate <file>` | Auditoria de código |
296
- | `cdp-edge infra` | Guia Cloudflare |
297
- | `cdp-edge --help` | Ajuda completa |
298
- | `cdp-edge --version` | Versão instalada |
212
+ ### "cdp-edge não é reconhecido"
299
213
 
300
- ---
214
+ O install não foi concluído. Execute separado e aguarde terminar:
301
215
 
302
- ## 🔧 SOLUÇÃO DE PROBLEMAS
216
+ ```bash
217
+ npm install -g cdp-edge
218
+ ```
219
+
220
+ ```bash
221
+ cdp-edge --version
222
+ ```
223
+
224
+ ---
303
225
 
304
- ### Erro: "Cannot find module dist/commands/install.js"
226
+ ### "Cannot find module dist/commands/install.js"
305
227
 
306
- O npm ainda tem a versão antiga em cache. Instale direto do GitHub para ter a versão mais recente:
228
+ Versão antiga em cache. Reinstale:
307
229
 
308
230
  ```bash
309
231
  npm uninstall -g cdp-edge
310
- npm install -g github:ricardosoli777/CDP-Edge-Premium
311
- cdp-edge --version
312
232
  ```
313
233
 
314
- ### Erro: "cdp-edge não é reconhecido"
315
-
316
234
  ```bash
317
- # Instalar globalmente
318
235
  npm install -g cdp-edge
319
-
320
- # Ou instalar direto do repositório
321
- npm install -g github:ricardosoli777/CDP-Edge-Premium
322
236
  ```
323
237
 
324
- ### Erro: "Permissão negada ao escrever arquivos"
238
+ ---
239
+
240
+ ### "Permissão negada"
325
241
 
326
242
  Execute o terminal como Administrador (Windows) ou use `sudo` (Mac/Linux).
327
243
 
328
- ### Erro: "Módulo não encontrado" (outros módulos)
244
+ ---
245
+
246
+ ### Nada foi criado na pasta após `cdp-edge install`
247
+
248
+ Confirme que o terminal está aberto dentro da pasta do projeto e rode:
329
249
 
330
250
  ```bash
331
- npm cache clean --force
332
- npm uninstall -g cdp-edge
333
- npm install -g cdp-edge
251
+ cdp-edge install . --name "Nome do Projeto"
334
252
  ```
335
253
 
336
254
  ---
337
255
 
338
- ## 🖱️ HUMAN-BEHAVIOR ENGINE (O MOTOR DE INTENÇÃO)
256
+ ## 🖱️ HUMAN-BEHAVIOR ENGINE
339
257
 
340
- A joia da coroa do CDP Edge. Capturamos o que o usuário **sente** e **faz**, e não apenas onde ele clica.
258
+ Capturamos o que o usuário **sente** e **faz**, não apenas onde clica.
341
259
 
342
- ### 🌡️ Engagement Scoring Engine (0-100)
343
- Cada ação do usuário soma (ou subtrai) pontos em tempo real:
344
- * **Scroll (25-90%)**: +5 a +15 pontos.
345
- * **VSL Watch (25-100%)**: +10 a +50 pontos.
346
- * **Copy Intent**: +20 pontos ao copiar cupons ou chaves PIX.
347
- * **Form Interaction**: +10 pontos por campo preenchido.
348
- * **Rage Click**: -10 pontos (sinal de frustração técnica).
349
- * **Gatilho Hot Lead**: Ao atingir **80 pontos**, disparar `High_Intent_Lead` para as plataformas.
260
+ | Evento | Pontuação |
261
+ |--------|-----------|
262
+ | Scroll 2590% | +5 a +15 pts |
263
+ | VSL Watch 25100% | +10 a +50 pts |
264
+ | Copy Intent (cupom, PIX) | +20 pts |
265
+ | Preenchimento de campo | +10 pts |
266
+ | Rage Click | -10 pts |
267
+ | **Hot Lead (80+ pts)** | **Dispara High_Intent_Lead** |
350
268
 
351
- ### 🎥 VSL & Video Tracker
352
- Monitoramento nativo de retenção em vídeos YouTube e Vimeo sem necessidade de scripts externos pesados.
269
+ **VSL & Video Tracker:** Monitoramento nativo de retenção em YouTube, Vimeo e HTML5 — dropout heatmap incluso.
353
270
 
354
271
  ---
355
272
 
356
273
  ## 📞 SUPORTE
357
274
 
358
- - **Documentação**: Verifique `CLAUDE.md` para padrões de desenvolvimento
359
275
  - **Issues**: https://github.com/ricardosoli777/CDP-Edge-Premium/issues
360
276
  - **Releases**: https://github.com/ricardosoli777/CDP-Edge-Premium/releases
361
277
 
@@ -120,7 +120,7 @@ A coluna `wamid` tem índice UNIQUE — garante que a mesma mensagem não seja p
120
120
  2. Menu lateral → **WhatsApp** → **Configuration**
121
121
  3. Seção **Webhook** → clique em **Edit**
122
122
  4. Preencha:
123
- - **Callback URL:** `https://server-edge-tracker.suporte-ed9.workers.dev/webhook/whatsapp`
123
+ - **Callback URL:** `https://SEU_WORKER.SEU_USUARIO.workers.dev/webhook/whatsapp`
124
124
  - **Verify Token:** valor do secret `WA_WEBHOOK_VERIFY_TOKEN`
125
125
  5. Clique em **Verify and Save**
126
126
  6. Após verificar, clique em **Manage** → ative o campo **`messages`**
@@ -161,7 +161,7 @@ Depois do `Contact` inicial, você pode enviar eventos adicionais conforme o lea
161
161
  Exemplo de chamada para registrar uma venda fechada pelo WhatsApp:
162
162
 
163
163
  ```javascript
164
- fetch('https://server-edge-tracker.suporte-ed9.workers.dev/track', {
164
+ fetch('https://SEU_WORKER.SEU_USUARIO.workers.dev/track', {
165
165
  method: 'POST',
166
166
  headers: { 'Content-Type': 'application/json' },
167
167
  body: JSON.stringify({
@@ -27,10 +27,10 @@ Enquanto o `server-tracking-agent` define **o que o Worker FAZ**, você define *
27
27
  ### Worker Ativo
28
28
  ```
29
29
  Nome: server-edge-tracker
30
- URL: https://server-edge-tracker.suporte-ed9.workers.dev
31
- Account: suporte@kadoshmkt.com.br
32
- ID: ed96c1aa212ab5ab2e97e522b9a0b49b
33
- Deploy: 2026-03-29 (último)
30
+ URL: https://SEU_WORKER.SEU_USUARIO.workers.dev
31
+ Account: SEU_EMAIL@SEUDOMINIO.com.br
32
+ ID: SEU_CLOUDFLARE_ACCOUNT_ID
33
+ Deploy: (data do último deploy)
34
34
  ```
35
35
 
36
36
  ### `wrangler.toml` — Estado Real
@@ -45,13 +45,13 @@ compatibility_flags = ["nodejs_compat"]
45
45
  META_PIXEL_ID = "SEU_PIXEL_ID"
46
46
  GA4_MEASUREMENT_ID = "G-XXXXXXXXXX"
47
47
  TIKTOK_PIXEL_ID = "CXXXXXXXXXXXXXXX"
48
- SITE_DOMAIN = "server-edge-tracker.suporte-ed9.workers.dev"
48
+ SITE_DOMAIN = "SEU_DOMINIO"
49
49
 
50
50
  # ── D1 Database ───────────────────────────────────────────────────────────────
51
51
  [[d1_databases]]
52
52
  binding = "DB"
53
53
  database_name = "cdp-edge-db"
54
- database_id = "7867d38f-5fa8-4c17-b465-386211422c09"
54
+ database_id = "SEU_D1_DATABASE_ID"
55
55
 
56
56
  # ── Workers AI ────────────────────────────────────────────────────────────────
57
57
  [ai]
@@ -67,7 +67,7 @@ crons = ["0 2 * * 7", "0 3 1 * *"]
67
67
  ## 🗄️ BINDING 1 — D1 DATABASE (`env.DB`)
68
68
 
69
69
  ### Banco: `cdp-edge-db`
70
- - **ID:** `7867d38f-5fa8-4c17-b465-386211422c09`
70
+ - **ID:** `SEU_D1_DATABASE_ID`
71
71
  - **Região:** ENAM (US East)
72
72
  - **Engine:** SQLite (Cloudflare D1)
73
73
  - **Tabelas ativas:** 8
@@ -0,0 +1,149 @@
1
+ # DevOps Agent — CDP Edge
2
+
3
+ Você é o **Agente DevOps exclusivo** do CDP Edge. Nenhum outro agente pode executar deploys ou operações de infraestrutura Cloudflare. Toda operação de deploy passa obrigatoriamente por você.
4
+
5
+ ---
6
+
7
+ ## ⚠️ AUTORIDADE EXCLUSIVA
8
+
9
+ | Operação | Exclusivo? |
10
+ |---|---|
11
+ | `wrangler deploy` | SIM — só você |
12
+ | `wrangler secret put` | SIM — só você |
13
+ | `wrangler d1 execute` (migrações) | SIM — só você |
14
+ | `wrangler kv namespace create` | SIM — só você |
15
+ | Rollback de versão | SIM — só você |
16
+
17
+ Outros agentes que precisarem de deploy **delegam para você** via `*deploy`.
18
+
19
+ ---
20
+
21
+ ## CICLO DE DEPLOY AUTOMÁTICO
22
+
23
+ ### Comando: `*deploy`
24
+
25
+ Executa o ciclo completo sem intervenção manual:
26
+
27
+ ```
28
+ 1. Recebe os dados reais do Memory Agent
29
+
30
+ 2. Escreve temporariamente no wrangler.toml:
31
+ - META_PIXEL_ID, GA4_MEASUREMENT_ID, TIKTOK_PIXEL_ID, SITE_DOMAIN
32
+ - database_id (D1)
33
+ - id + preview_id (KV)
34
+ - [[routes]] do domínio do cliente
35
+
36
+ 3. Executa: wrangler deploy
37
+
38
+ 4. Confirma sucesso (Version ID + triggers ativos)
39
+
40
+ 5. Reverte IMEDIATAMENTE todos os valores para placeholder
41
+
42
+ 6. Confirma que CDP Edge está limpo (git status)
43
+ ```
44
+
45
+ **O wrangler.toml nunca fica com dados reais após o deploy.**
46
+
47
+ ---
48
+
49
+ ## PROCEDURE `*deploy`
50
+
51
+ ```bash
52
+ # Passo 1 — Receber do Memory Agent:
53
+ # - META_PIXEL_ID, GA4_MEASUREMENT_ID, TIKTOK_PIXEL_ID
54
+ # - SITE_DOMAIN, D1_DATABASE_ID, KV_ID, KV_PREVIEW_ID
55
+
56
+ # Passo 2 — Aplicar temporariamente no wrangler.toml
57
+ # (substituir placeholders pelos valores reais)
58
+
59
+ # Passo 3 — Deploy
60
+ cd server-edge-tracker
61
+ wrangler deploy
62
+
63
+ # Passo 4 — Reverter IMEDIATAMENTE
64
+ # (substituir valores reais pelos placeholders)
65
+
66
+ # Passo 5 — Verificar limpeza
67
+ git status
68
+ # Esperado: "nothing to commit, working tree clean"
69
+ # Se modificado: git checkout server-edge-tracker/wrangler.toml
70
+ ```
71
+
72
+ ---
73
+
74
+ ## PROCEDURE `*migrate`
75
+
76
+ Aplica migrações D1 em ordem:
77
+
78
+ ```bash
79
+ wrangler d1 execute cdp-edge-db --file=migrate-v2.sql --remote
80
+ wrangler d1 execute cdp-edge-db --file=migrate-v3.sql --remote
81
+ wrangler d1 execute cdp-edge-db --file=migrate-v4.sql --remote
82
+ wrangler d1 execute cdp-edge-db --file=migrate-v5.sql --remote
83
+ wrangler d1 execute cdp-edge-db --file=migrate-v6.sql --remote
84
+ ```
85
+
86
+ Após cada migração: confirmar sucesso antes de prosseguir.
87
+
88
+ ---
89
+
90
+ ## PROCEDURE `*rollback`
91
+
92
+ Reverte para versão anterior do Worker:
93
+
94
+ ```bash
95
+ # Listar versões disponíveis
96
+ wrangler deployments list
97
+
98
+ # Fazer rollback para versão específica
99
+ wrangler rollback [VERSION_ID]
100
+ ```
101
+
102
+ ---
103
+
104
+ ## PROCEDURE `*secrets`
105
+
106
+ Configura todos os secrets do cliente na Cloudflare:
107
+
108
+ ```bash
109
+ # Obrigatórios
110
+ wrangler secret put META_ACCESS_TOKEN
111
+ wrangler secret put GA4_API_SECRET
112
+ wrangler secret put WA_ACCESS_TOKEN
113
+ wrangler secret put WA_PHONE_ID
114
+ wrangler secret put WA_NOTIFY_NUMBER
115
+ wrangler secret put WA_WEBHOOK_VERIFY_TOKEN
116
+
117
+ # Opcionais (conforme plataformas selecionadas)
118
+ wrangler secret put TIKTOK_ACCESS_TOKEN
119
+ wrangler secret put PINTEREST_ACCESS_TOKEN
120
+ wrangler secret put REDDIT_ACCESS_TOKEN
121
+ wrangler secret put LINKEDIN_ACCESS_TOKEN
122
+ wrangler secret put SPOTIFY_ACCESS_TOKEN
123
+ wrangler secret put CALLMEBOT_PHONE
124
+ wrangler secret put CALLMEBOT_APIKEY
125
+ ```
126
+
127
+ ---
128
+
129
+ ## PROCEDURE `*smoke-test`
130
+
131
+ Valida se o Worker está operacional após deploy:
132
+
133
+ ```bash
134
+ # Testar endpoint de health ativo
135
+ curl https://SEU_DOMINIO/health
136
+
137
+ # Resultado esperado: todos os bindings OK
138
+ # Se algum MISSING: investigar e corrigir antes de prosseguir
139
+ ```
140
+
141
+ ---
142
+
143
+ ## REGRAS
144
+
145
+ 1. **Sempre** verificar `git status` após reverter placeholders
146
+ 2. **Nunca** commitar com dados reais — se acontecer, reverter imediatamente com `git checkout`
147
+ 3. **Sempre** confirmar Version ID após deploy bem-sucedido
148
+ 4. **Sempre** rodar `*smoke-test` após `*deploy`
149
+ 5. Qualquer falha de deploy: reportar ao Master Orchestrator com o erro completo
@@ -47,7 +47,7 @@ Cloudflare Dashboard
47
47
  → Add record
48
48
  → Type: CNAME
49
49
  → Name: track
50
- → Target: server-edge-tracker.suporte-ed9.workers.dev
50
+ → Target: SEU_WORKER.SEU_USUARIO.workers.dev
51
51
  → Proxy status: Proxied (nuvem laranja ☁️)
52
52
  → TTL: Auto
53
53
  → Save
@@ -64,7 +64,7 @@ curl -X POST "https://api.cloudflare.com/client/v4/zones/{ZONE_ID}/dns_records"
64
64
  --data '{
65
65
  "type": "CNAME",
66
66
  "name": "track",
67
- "content": "server-edge-tracker.suporte-ed9.workers.dev",
67
+ "content": "SEU_WORKER.SEU_USUARIO.workers.dev",
68
68
  "proxied": true
69
69
  }'
70
70
  ```
@@ -115,7 +115,7 @@ Localizar e substituir no `wrangler.toml`:
115
115
 
116
116
  ```toml
117
117
  # ANTES:
118
- SITE_DOMAIN = "server-edge-tracker.suporte-ed9.workers.dev"
118
+ SITE_DOMAIN = "SEU_WORKER.SEU_USUARIO.workers.dev"
119
119
 
120
120
  # DEPOIS:
121
121
  SITE_DOMAIN = "clientdomain.com"
@@ -177,7 +177,7 @@ O `cdpTrack.js` do cliente deve apontar para o novo endpoint:
177
177
 
178
178
  ```javascript
179
179
  // ANTES:
180
- const CDP_ENDPOINT = 'https://server-edge-tracker.suporte-ed9.workers.dev/track';
180
+ const CDP_ENDPOINT = 'https://SEU_WORKER.SEU_USUARIO.workers.dev/track';
181
181
 
182
182
  // DEPOIS:
183
183
  const CDP_ENDPOINT = 'https://track.clientdomain.com/track';
@@ -5,6 +5,18 @@ Sua função: **coordenar os agentes especialistas, monitorar outputs e garantir
5
5
 
6
6
  ---
7
7
 
8
+ ## IDENTIDADE DO PROJETO
9
+
10
+ O CDP Edge **não é um projeto de cliente.** É um **Squad de Agentes AI** cuja única e exclusiva missão é criar soluções de rastreamento premium para projetos externos.
11
+
12
+ - Nenhuma credencial, domínio, ID de pixel, token ou dado de cliente pertence a este repositório
13
+ - Toda implementação gerada é entregue para o projeto do cliente — nunca salva aqui
14
+ - O CDP Edge é a fábrica. Os projetos gerados são os produtos finais — criados 100% dentro do Cloudflare
15
+
16
+ ---
17
+
18
+ ---
19
+
8
20
  ## ARQUITETURA DO SISTEMA
9
21
 
10
22
  ```
@@ -59,6 +71,9 @@ Master Orchestrator (você)
59
71
  │ ├── Code Guardian Agent → monitoramento contínuo de integridade
60
72
  │ └── Memory Agent → cofre anti-alucinação, contexto de sessão
61
73
 
74
+ ├── 🔧 DEVOPS
75
+ │ └── DevOps Agent → deploy exclusivo, secrets, migrations, rollback, smoke-test
76
+
62
77
  └── 🚀 Enterprise Agents (Premium Tracking)
63
78
  ├── Attribution Agent → multi-touch attribution 7+ modelos
64
79
  ├── Security Enterprise Agent → rate limiting, IP blocking, audit logging
@@ -132,6 +147,9 @@ SKILL_BASE: [diretório da skill tracking-events-generator]
132
147
  ├── debug-agent.md ← diagnóstico de eventos e falhas
133
148
  ├── code-guardian-agent.md ← monitoramento contínuo de integridade
134
149
 
150
+ ├── ── DEVOPS ──
151
+ ├── devops-agent.md ← deploy exclusivo, secrets, migrations, rollback, smoke-test
152
+
135
153
  └── ── ENTERPRISE (Premium Tracking) ──
136
154
  ├── attribution-agent.md ← multi-touch attribution 7+ modelos
137
155
  ├── security-enterprise-agent.md ← rate limiting, IP blocking, audit
@@ -157,7 +175,7 @@ PASSO 2: Seleção de plataformas (múltipla escolha — 9 plataformas + gateway
157
175
 
158
176
  FASE 0.5: Intelligence Agent (opcional, atualizações de API)
159
177
 
160
- FASE 1: Acesso ao projeto (request_cowork_directory)
178
+ FASE 1: Acesso à página do cliente (duas opções — ver abaixo)
161
179
 
162
180
  FASE 2: Page Analyzer Agent (análise de páginas)
163
181
 
@@ -172,16 +190,40 @@ FASE 6: Enterprise Features (opcional, Attribution, Security, Performance, Compl
172
190
 
173
191
  FASE 7: Validação (Validator Agent + Correção Automática)
174
192
 
175
- FASE 8: Relatório FinalEntrega ao usuário + Escrita de Checkpoint
193
+ FASE 8: DevOps Agent*secrets + *deploy + *smoke-test
194
+
195
+ FASE 9: Relatório Final → Entrega ao usuário + Escrita de Checkpoint
176
196
  ```
177
197
 
178
198
  ---
179
199
 
180
200
  ## 🎯 RESPONSABILIDADES DE CADA AGENTE (Quando Entra em Ação)
181
201
 
202
+ ### 🔵 FASE 1: Acesso à Página do Cliente
203
+
204
+ **ENTRA EM AÇÃO:** Após coleta de credenciais e seleção de plataformas
205
+
206
+ Perguntar ao cliente qual opção se aplica:
207
+
208
+ **Opção A — Página no Cloudflare Pages (recomendado)**
209
+ - A página já está publicada no ecossistema Cloudflare
210
+ - Análise feita na URL real com Worker e cookie já ativos no mesmo ambiente
211
+ - Preview deployments disponíveis para validar antes de publicar para tráfego real
212
+ - **Ação:** solicitar a URL pública da página no Cloudflare Pages
213
+
214
+ **Opção B — URL externa**
215
+ - Página hospedada fora da Cloudflare (Hotmart, Elementor, servidor próprio, etc.)
216
+ - Page Analyzer acessa a URL e analisa o HTML renderizado
217
+ - O `cdpTrack.js` gerado aponta para o Worker do cliente independente do host
218
+ - **Ação:** solicitar a URL pública da página
219
+
220
+ > Em ambos os casos o endpoint `/track` reside no Worker Cloudflare do cliente — o host da página não afeta a arquitetura de tracking.
221
+
222
+ ---
223
+
182
224
  ### 🔴 FASE 2: Page Analyzer Agent
183
225
 
184
- **ENTRA EM AÇÃO:** Após FASE 1 (acesso ao projeto)
226
+ **ENTRA EM AÇÃO:** Após FASE 1 (URL da página fornecida pelo cliente)
185
227
 
186
228
  **RESPONSABILIDADE:**
187
229
  - Ler todos os arquivos do projeto (HTML, JSX, TSX)
@@ -5,6 +5,55 @@ Como as conversas de desenvolvimento duram o dia todo e são super longas, a Int
5
5
 
6
6
  ---
7
7
 
8
+ ## ⚠️ REGRA ABSOLUTA — CICLO DE VIDA DOS DADOS
9
+
10
+ O CDP Edge é uma fábrica. Você é a memória **temporária** da sessão de trabalho.
11
+
12
+ | O que você armazena | Onde fica | Quando é apagado |
13
+ |---|---|---|
14
+ | IDs de infraestrutura (D1, KV, Queues) | Apenas em memória de sessão | Ao final do projeto |
15
+ | Tokens e API Keys do cliente | Apenas em memória de sessão | Ao final do projeto |
16
+ | Domínios e URLs do cliente | Apenas em memória de sessão | Ao final do projeto |
17
+ | Pixel IDs e credenciais de plataformas | Apenas em memória de sessão | Ao final do projeto |
18
+
19
+ **NUNCA** persista dados reais do cliente em arquivos do projeto CDP Edge.
20
+ **NUNCA** salve IDs, tokens ou URLs reais no `wrangler.toml`, `worker.js` ou qualquer arquivo do repositório.
21
+ **SEMPRE** apague o `memory-agent.json` ao encerrar o projeto.
22
+
23
+ O destino final de todos os dados reais é exclusivamente dentro da **Cloudflare** — via `wrangler secret put` e `wrangler.toml` do projeto do cliente, nunca aqui.
24
+
25
+ ---
26
+
27
+ ## 🚀 PROCEDURE `*deploy` — Ciclo Automatizado
28
+
29
+ Quando o Master Orchestrator solicitar um deploy, você fornece os dados ao DevOps Agent nesta ordem:
30
+
31
+ ```
32
+ 1. Entregar ao DevOps Agent:
33
+ - META_PIXEL_ID → pixel real do cliente
34
+ - GA4_MEASUREMENT_ID → ID real do GA4
35
+ - TIKTOK_PIXEL_ID → pixel real do TikTok
36
+ - SITE_DOMAIN → domínio raiz do cliente
37
+ - D1_DATABASE_ID → ID real do banco D1
38
+ - KV_NAMESPACE_ID → ID real do KV
39
+ - KV_PREVIEW_ID → ID preview do KV
40
+ - ROUTES → domínio/track* e *.dominio/track*
41
+
42
+ 2. DevOps Agent executa o ciclo completo:
43
+ escreve → deploya → reverte → confirma limpeza
44
+
45
+ 3. Você registra no memory-agent.json:
46
+ - Version ID do deploy
47
+ - Timestamp
48
+ - Status: success | failed
49
+ ```
50
+
51
+ **Você nunca executa o deploy diretamente — sempre delega ao DevOps Agent.**
52
+
53
+ ---
54
+
55
+ ---
56
+
8
57
  ## 🧠 OBJETIVO PRINCIPAL: ELIMINAR RETRABALHO E ALUCINAÇÃO
9
58
 
10
59
  Sua única função é registrar absolutamente TUDO o que importa. Você é o banco de dados centralizado da sessão de chat.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cdp-edge",
3
- "version": "1.12.0",
3
+ "version": "1.13.0",
4
4
  "description": "CDP Edge - Quantum Tracking - Sistema multi-agente para tracking digital Cloudflare Native (Workers + D1)",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -1,5 +1,5 @@
1
1
  # Setup Completo — server-edge-tracker
2
- ## groof.com.br | Meta CAPI v22.0 + GA4 Measurement Protocol + D1 Database
2
+ ## SEU_DOMINIO | Meta CAPI v22.0 + GA4 Measurement Protocol + D1 Database
3
3
 
4
4
  > Execute cada bloco no terminal, um de cada vez.
5
5
  > Tempo total estimado: 15–20 minutos.
@@ -197,8 +197,8 @@ Ainda com `META_TEST_CODE` configurado, rode este comando no terminal
197
197
  ```bash
198
198
  curl -X POST https://server-edge-tracker.seu-usuario.workers.dev/track \
199
199
  -H "Content-Type: application/json" \
200
- -H "Origin: https://groof.com.br" \
201
- -d "{\"eventName\":\"Lead\",\"email\":\"teste@email.com\",\"pageUrl\":\"https://groof.com.br/teste\"}"
200
+ -H "Origin: https://SEU_DOMINIO" \
201
+ -d "{\"eventName\":\"Lead\",\"email\":\"teste@email.com\",\"pageUrl\":\"https://SEU_DOMINIO/teste\"}"
202
202
  ```
203
203
 
204
204
  Resultado esperado:
@@ -221,11 +221,11 @@ wrangler deploy
221
221
 
222
222
  ## PASSO 11 — Configurar domínio personalizado (opcional)
223
223
 
224
- Se quiser usar `track.groof.com.br` em vez do domínio `.workers.dev`:
224
+ Se quiser usar `track.SEU_DOMINIO` em vez do domínio `.workers.dev`:
225
225
 
226
226
  1. No painel da Cloudflare → Workers & Pages → seu Worker → Settings → Domains & Routes
227
227
  2. Clique "Add Custom Domain"
228
- 3. Digite: `track.groof.com.br`
228
+ 3. Digite: `track.SEU_DOMINIO`
229
229
  4. Cloudflare configura o DNS automaticamente (como o domínio já está na Cloudflare)
230
230
 
231
231
  ---
@@ -243,8 +243,8 @@ Preencher:
243
243
  - **Formato:** `JSON`
244
244
  - **Evento:** marcar **Venda Realizada** (status `paid`)
245
245
 
246
- > Se usar domínio personalizado (ex: `track.groof.com.br`):
247
- > URL fica: `https://track.groof.com.br/webhook/ticto`
246
+ > Se usar domínio personalizado (ex: `track.SEU_DOMINIO`):
247
+ > URL fica: `https://track.SEU_DOMINIO/webhook/ticto`
248
248
 
249
249
  **Testar:** na tela de webhook da Ticto há um botão **"Enviar teste"**. Ao clicar, a Ticto envia um POST simulado. Confirme que o evento aparece no Gerenciador de Eventos do Meta como `Purchase` e que o dado foi registrado no banco D1 (ver comando no final deste guia).
250
250
 
@@ -296,7 +296,7 @@ Preencher:
296
296
  "userId": "usr_abc123",
297
297
  "gaClientId": "GA1.1.123456789.1234567890",
298
298
  "eventId": "CDP_1234567890_abc123",
299
- "pageUrl": "https://groof.com.br/obrigado",
299
+ "pageUrl": "https://SEU_DOMINIO/obrigado",
300
300
  "value": 297,
301
301
  "currency": "BRL",
302
302
  "utmSource": "facebook",
@@ -1,5 +1,5 @@
1
1
  -- CDP Edge — Schema D1
2
- -- Projeto: server-edge-tracker | groof.com.br
2
+ -- Projeto: server-edge-tracker | SEU_DOMINIO
3
3
  -- Criação: wrangler d1 execute cdp-edge-db --file=schema.sql
4
4
 
5
5
  -- ── Tabela de Leads ───────────────────────────────────────────────────────────
@@ -16,15 +16,15 @@
16
16
  */
17
17
 
18
18
  // ── Constantes ────────────────────────────────────────────────────────────────
19
- const META_PIXEL_ID = '1234567890123456'; // Substitua pelo seu Pixel ID
20
- const GA4_MEASUREMENT_ID = 'G-XXXXXXXXXX'; // Substitua pelo seu ID GA4
21
- const TIKTOK_PIXEL_ID = 'CXXXXXXXXXXXXXXX'; // Substitua pelo seu Pixel TikTok
22
- const ALLOWED_ORIGINS = [
23
- 'https://seu-dominio.com.br', // Substitua pelo URL absoluto de origem do seu funil
24
- 'https://seu-worker-tracking.seu-usuario.workers.dev', // URL real do Cloudflare Worker para CORS
25
- 'http://localhost:3000', // Desenvolvimento local Next
26
- 'http://localhost:5173', // Desenvolvimento local Vite
27
- ];
19
+ // IDs de pixel lidos exclusivamente de env.* (wrangler.toml [vars] ou wrangler secret put)
20
+ // CORS aceita o domínio raiz e qualquer subdomínio (domínio vem de env.SITE_DOMAIN)
21
+ function isAllowedOrigin(origin, siteDomain) {
22
+ if (!origin || !siteDomain) return false;
23
+ return origin === `https://${siteDomain}`
24
+ || origin.endsWith(`.${siteDomain}`)
25
+ || origin === 'http://localhost:3000'
26
+ || origin === 'http://localhost:5173';
27
+ }
28
28
 
29
29
  // ── SHA-256 via WebCrypto (obrigatório no Cloudflare Workers) ─────────────────
30
30
  async function sha256(value) {
@@ -60,8 +60,8 @@ function normalizeCity(city) {
60
60
  }
61
61
 
62
62
  // ── CORS ──────────────────────────────────────────────────────────────────────
63
- function corsHeaders(origin) {
64
- const allowed = ALLOWED_ORIGINS.includes(origin) ? origin : ALLOWED_ORIGINS[0];
63
+ function corsHeaders(origin, siteDomain) {
64
+ const allowed = isAllowedOrigin(origin, siteDomain) ? origin : `https://${siteDomain}`;
65
65
  return {
66
66
  'Access-Control-Allow-Origin': allowed,
67
67
  'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
@@ -121,7 +121,7 @@ async function sendMetaCapi(env, eventName, payload, request, ctx) {
121
121
  event_name: eventName,
122
122
  event_time: Math.floor(Date.now() / 1000),
123
123
  event_id: eventId || `cdp_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
124
- event_source_url: pageUrl || `https://server-edge-tracker.suporte-ed9.workers.dev`,
124
+ event_source_url: pageUrl || `https://${env.SITE_DOMAIN}`,
125
125
  action_source: 'website',
126
126
  user_data: userData,
127
127
  ...(Object.keys(customData).length > 0 && { custom_data: customData }),
@@ -137,7 +137,7 @@ async function sendMetaCapi(env, eventName, payload, request, ctx) {
137
137
  requestBody.test_event_code = env.META_TEST_CODE;
138
138
  }
139
139
 
140
- const endpoint = `https://graph.facebook.com/v22.0/${META_PIXEL_ID}/events`;
140
+ const endpoint = `https://graph.facebook.com/v22.0/${env.META_PIXEL_ID}/events`;
141
141
 
142
142
  try {
143
143
  const res = await fetch(endpoint, {
@@ -220,7 +220,7 @@ async function sendGA4Mp(env, ga4EventName, payload, ctx) {
220
220
  };
221
221
 
222
222
  const url = `https://www.google-analytics.com/mp/collect`
223
- + `?measurement_id=${GA4_MEASUREMENT_ID}`
223
+ + `?measurement_id=${env.GA4_MEASUREMENT_ID}`
224
224
  + `&api_secret=${env.GA4_API_SECRET}`;
225
225
 
226
226
  try {
@@ -771,7 +771,7 @@ async function sendTikTokApi(env, eventName, payload, request, ctx) {
771
771
  event_id: eventId || `cdp_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
772
772
  user,
773
773
  page: {
774
- url: pageUrl || 'https://server-edge-tracker.suporte-ed9.workers.dev',
774
+ url: pageUrl || `https://${env.SITE_DOMAIN}`,
775
775
  referrer: request.headers.get('Referer') || '',
776
776
  },
777
777
  ...(Object.keys(properties).length > 0 && { properties }),
@@ -1158,20 +1158,107 @@ async function sendSpotifyCapi(env, eventName, payload, request, ctx) {
1158
1158
  }
1159
1159
 
1160
1160
 
1161
- // ── WhatsApp — Meta Cloud API v22.0 (notificações ao dono) ───────────────────
1161
+ // ── WhatsApp — Meta Cloud API v22.0 ──────────────────────────────────────────
1162
1162
  //
1163
1163
  // Secrets necessários (wrangler secret put):
1164
1164
  // WA_PHONE_ID → ID do número no WhatsApp Business (ex: 123456789012345)
1165
1165
  // WA_ACCESS_TOKEN → Token permanente da Meta Cloud API
1166
1166
  // WA_NOTIFY_NUMBER → Número do dono para receber notificações (ex: 5511999998888)
1167
1167
  //
1168
- // Usado para: avisos de Nova Venda e Novo Lead em tempo real.
1168
+ // Formatos suportados:
1169
+ // text → Texto livre (só funciona dentro da janela de 24h)
1170
+ // template → Mensagem pré-aprovada pela Meta (inicia conversa proativamente)
1171
+ // image → Imagem com legenda opcional (URL pública)
1172
+ // video → Vídeo com legenda opcional (URL pública)
1173
+ // document → PDF/arquivo com nome e legenda (URL pública)
1174
+ // audio → Áudio (URL pública, OGG/MP4)
1175
+ // interactive → Botões (até 3) ou lista de opções (até 10 itens)
1176
+ //
1177
+ // Regra crítica: para iniciar conversa proativamente (Purchase, Lead, etc.)
1178
+ // é OBRIGATÓRIO usar type: 'template'. Texto livre só funciona em resposta
1179
+ // a uma mensagem do usuário nos últimos 24h.
1169
1180
  //
1170
- async function sendWhatsApp(env, tipo, payload) {
1181
+ async function sendWhatsApp(env, tipo, payload, options = {}) {
1171
1182
  if (!env.WA_PHONE_ID || !env.WA_ACCESS_TOKEN || !env.WA_NOTIFY_NUMBER) {
1172
1183
  return { skipped: 'WhatsApp não configurado' };
1173
1184
  }
1174
1185
 
1186
+ const to = options.to || env.WA_NOTIFY_NUMBER;
1187
+
1188
+ // ── Template (proativo — fora da janela de 24h) ───────────────────────────
1189
+ // Usar quando: Purchase, Lead, ou qualquer disparo iniciado pelo sistema
1190
+ // O template deve estar aprovado no Meta Business Suite → WhatsApp → Templates
1191
+ // Formato dos componentes segue a API de Templates da Meta
1192
+ if (options.template) {
1193
+ const { name, language = 'pt_BR', components = [] } = options.template;
1194
+ const body = {
1195
+ messaging_product: 'whatsapp',
1196
+ to,
1197
+ type: 'template',
1198
+ template: { name, language: { code: language }, components },
1199
+ };
1200
+ return _sendWARequest(env, body);
1201
+ }
1202
+
1203
+ // ── Mídia — image, video, document, audio ────────────────────────────────
1204
+ // Usar quando: envio de PDF de nota fiscal, vídeo de boas-vindas, etc.
1205
+ // mediaUrl deve ser uma URL pública acessível pela Meta
1206
+ if (options.mediaType && options.mediaUrl) {
1207
+ const mediaPayload = { link: options.mediaUrl };
1208
+ if (options.caption) mediaPayload.caption = options.caption;
1209
+ if (options.filename) mediaPayload.filename = options.filename; // só para document
1210
+ const body = {
1211
+ messaging_product: 'whatsapp',
1212
+ to,
1213
+ type: options.mediaType,
1214
+ [options.mediaType]: mediaPayload,
1215
+ };
1216
+ return _sendWARequest(env, body);
1217
+ }
1218
+
1219
+ // ── Interactive — botões (até 3) ─────────────────────────────────────────
1220
+ // Usar quando: confirmação de compra com botões de ação
1221
+ // buttons: [{ id: 'btn_1', title: 'Ver Pedido' }, ...]
1222
+ if (options.interactive === 'buttons' && options.buttons?.length) {
1223
+ const body = {
1224
+ messaging_product: 'whatsapp',
1225
+ to,
1226
+ type: 'interactive',
1227
+ interactive: {
1228
+ type: 'button',
1229
+ body: { text: options.bodyText || '' },
1230
+ action: {
1231
+ buttons: options.buttons.slice(0, 3).map(b => ({
1232
+ type: 'reply',
1233
+ reply: { id: b.id, title: b.title },
1234
+ })),
1235
+ },
1236
+ },
1237
+ };
1238
+ return _sendWARequest(env, body);
1239
+ }
1240
+
1241
+ // ── Interactive — lista de opções (até 10 itens) ──────────────────────────
1242
+ // Usar quando: menu de suporte, seleção de produto, etc.
1243
+ // rows: [{ id: 'opt_1', title: 'Suporte', description: 'Falar com equipe' }, ...]
1244
+ if (options.interactive === 'list' && options.rows?.length) {
1245
+ const body = {
1246
+ messaging_product: 'whatsapp',
1247
+ to,
1248
+ type: 'interactive',
1249
+ interactive: {
1250
+ type: 'list',
1251
+ body: { text: options.bodyText || '' },
1252
+ action: {
1253
+ button: options.listButton || 'Ver opções',
1254
+ sections: [{ rows: options.rows.slice(0, 10) }],
1255
+ },
1256
+ },
1257
+ };
1258
+ return _sendWARequest(env, body);
1259
+ }
1260
+
1261
+ // ── Text — fallback (dentro da janela de 24h) ─────────────────────────────
1175
1262
  const nome = [payload.firstName, payload.lastName].filter(Boolean).join(' ') || 'sem nome';
1176
1263
  const valor = payload.value ? `R$ ${parseFloat(payload.value).toFixed(2)}` : '—';
1177
1264
  const utm = payload.utmSource || 'direto';
@@ -1196,9 +1283,19 @@ async function sendWhatsApp(env, tipo, payload) {
1196
1283
  `🌐 ${payload.pageUrl || '—'}\n` +
1197
1284
  `🕐 ${new Date().toLocaleString('pt-BR', { timeZone: 'America/Sao_Paulo' })}`;
1198
1285
  } else {
1199
- return { skipped: `tipo ${tipo} não notificado` };
1286
+ return { skipped: `tipo ${tipo} não suportado sem template` };
1200
1287
  }
1201
1288
 
1289
+ return _sendWARequest(env, {
1290
+ messaging_product: 'whatsapp',
1291
+ to,
1292
+ type: 'text',
1293
+ text: { body: texto },
1294
+ });
1295
+ }
1296
+
1297
+ // ── Executor interno — evita duplicação de fetch entre os formatos ────────────
1298
+ async function _sendWARequest(env, body) {
1202
1299
  try {
1203
1300
  const res = await fetch(`https://graph.facebook.com/v22.0/${env.WA_PHONE_ID}/messages`, {
1204
1301
  method: 'POST',
@@ -1206,14 +1303,11 @@ async function sendWhatsApp(env, tipo, payload) {
1206
1303
  'Content-Type': 'application/json',
1207
1304
  'Authorization': `Bearer ${env.WA_ACCESS_TOKEN}`,
1208
1305
  },
1209
- body: JSON.stringify({
1210
- messaging_product: 'whatsapp',
1211
- to: env.WA_NOTIFY_NUMBER,
1212
- type: 'text',
1213
- text: { body: texto },
1214
- }),
1306
+ body: JSON.stringify(body),
1215
1307
  });
1216
- return { ok: res.ok, status: res.status };
1308
+ const data = await res.json();
1309
+ if (!res.ok) console.error('WhatsApp Meta API error:', JSON.stringify(data));
1310
+ return { ok: res.ok, status: res.status, data };
1217
1311
  } catch (err) {
1218
1312
  console.error('WhatsApp Meta API failed:', err.message);
1219
1313
  return { ok: false, error: err.message };
@@ -1956,7 +2050,7 @@ export default {
1956
2050
  const origin = request.headers.get('Origin') || '';
1957
2051
  const headers = {
1958
2052
  'Content-Type': 'application/json',
1959
- ...corsHeaders(origin),
2053
+ ...corsHeaders(origin, env.SITE_DOMAIN),
1960
2054
  };
1961
2055
 
1962
2056
  // Preflight CORS
@@ -1981,18 +2075,67 @@ export default {
1981
2075
  });
1982
2076
  }
1983
2077
 
1984
- // ── GET /health ───────────────────────────────────────────────────────────
2078
+ // ── GET /health — Smoke Test completo ────────────────────────────────────
1985
2079
  if (request.method === 'GET' && url.pathname === '/health') {
2080
+ const results = {};
2081
+
2082
+ // D1 — query real
2083
+ try {
2084
+ await env.DB.prepare('SELECT 1').run();
2085
+ results.d1 = 'ok';
2086
+ } catch (err) {
2087
+ results.d1 = `FAILED: ${err.message}`;
2088
+ }
2089
+
2090
+ // KV — leitura real
2091
+ try {
2092
+ await env.GEO_CACHE.get('__health_check__');
2093
+ results.kv = 'ok';
2094
+ } catch (err) {
2095
+ results.kv = `FAILED: ${err.message}`;
2096
+ }
2097
+
2098
+ // Workers AI — ping
2099
+ try {
2100
+ await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
2101
+ messages: [{ role: 'user', content: 'ping' }],
2102
+ max_tokens: 1,
2103
+ });
2104
+ results.ai = 'ok';
2105
+ } catch (err) {
2106
+ results.ai = `FAILED: ${err.message}`;
2107
+ }
2108
+
2109
+ // Vars obrigatórias
2110
+ const vars = {
2111
+ META_PIXEL_ID: env.META_PIXEL_ID ? 'set' : 'MISSING',
2112
+ GA4_MEASUREMENT_ID: env.GA4_MEASUREMENT_ID ? 'set' : 'MISSING',
2113
+ TIKTOK_PIXEL_ID: env.TIKTOK_PIXEL_ID ? 'set' : 'MISSING',
2114
+ SITE_DOMAIN: env.SITE_DOMAIN ? 'set' : 'MISSING',
2115
+ };
2116
+
2117
+ // Secrets obrigatórios
2118
+ const secrets = {
2119
+ META_ACCESS_TOKEN: env.META_ACCESS_TOKEN ? 'set' : 'MISSING',
2120
+ GA4_API_SECRET: env.GA4_API_SECRET ? 'set' : 'MISSING',
2121
+ WA_ACCESS_TOKEN: env.WA_ACCESS_TOKEN ? 'set' : 'MISSING',
2122
+ WA_NOTIFY_NUMBER: env.WA_NOTIFY_NUMBER ? 'set' : 'MISSING',
2123
+ TIKTOK_ACCESS_TOKEN: env.TIKTOK_ACCESS_TOKEN ? 'set' : 'not set (optional)',
2124
+ CALLMEBOT_PHONE: env.CALLMEBOT_PHONE ? 'set' : 'not set (optional)',
2125
+ };
2126
+
2127
+ const hasMissing =
2128
+ Object.values(vars).includes('MISSING') ||
2129
+ Object.values(secrets).includes('MISSING') ||
2130
+ results.d1 !== 'ok';
2131
+
1986
2132
  return new Response(JSON.stringify({
1987
- status: 'ok',
1988
- meta_pixel: META_PIXEL_ID,
1989
- ga4: GA4_MEASUREMENT_ID,
1990
- tiktok_pixel: env.TIKTOK_PIXEL_ID || TIKTOK_PIXEL_ID,
1991
- db: env.DB ? 'connected' : 'not bound',
1992
- meta_token: env.META_ACCESS_TOKEN ? 'set' : 'MISSING',
1993
- ga4_secret: env.GA4_API_SECRET ? 'set' : 'MISSING',
1994
- tiktok_token: env.TIKTOK_ACCESS_TOKEN ? 'set' : 'not set (optional)',
1995
- }), { headers });
2133
+ status: hasMissing ? 'degraded' : 'ok',
2134
+ timestamp: new Date().toISOString(),
2135
+ bindings: results,
2136
+ vars,
2137
+ secrets,
2138
+ }, null, 2), { headers });
1996
2139
  }
1997
2140
 
1998
2141
  // ── POST /track — evento do browser ───────────────────────────────────────
@@ -2153,7 +2296,7 @@ export default {
2153
2296
  }
2154
2297
 
2155
2298
  const resHeaders = new Headers(headers);
2156
- resHeaders.set('Set-Cookie', `_cdp_uid=${finalUserId}; HttpOnly; Secure; SameSite=Lax; Max-Age=31536000; Path=/`);
2299
+ resHeaders.set('Set-Cookie', `_cdp_uid=${finalUserId}; HttpOnly; Secure; SameSite=Lax; Max-Age=31536000; Path=/; Domain=.${env.SITE_DOMAIN}`);
2157
2300
 
2158
2301
  return new Response(JSON.stringify({
2159
2302
  ok: true,
@@ -2340,7 +2483,7 @@ export default {
2340
2483
 
2341
2484
  // ── POST /webhook/ticto ───────────────────────────────────────────────────
2342
2485
  // Ticto Webhook v2 (JSON) — configurar em: Produto → Webhooks → Versão 2.0 → JSON
2343
- // URL a cadastrar na Ticto: https://server-edge-tracker.suporte-ed9.workers.dev/webhook/ticto
2486
+ // URL a cadastrar na Ticto: https://SEU_DOMINIO/webhook/ticto
2344
2487
  // Evento a selecionar: "Venda Realizada" (status: paid | approved | complete)
2345
2488
  if (request.method === 'POST' && url.pathname === '/webhook/ticto') {
2346
2489
  // Validação HMAC-SHA256 Ticto (X-Ticto-Signature)
@@ -3,12 +3,30 @@ main = "worker.js"
3
3
  compatibility_date = "2025-01-01"
4
4
  compatibility_flags = ["nodejs_compat"]
5
5
 
6
+ # ── Worker Routes — same-domain tracking (imune a bloqueios) ─────────────────
7
+ # Substituir SEU_DOMINIO pelo domínio do cliente antes do deploy
8
+ # [[routes]]
9
+ # pattern = "SEU_DOMINIO/track*"
10
+ # zone_name = "SEU_DOMINIO"
11
+ #
12
+ # [[routes]]
13
+ # pattern = "*.SEU_DOMINIO/track*"
14
+ # zone_name = "SEU_DOMINIO"
15
+
16
+ [[routes]]
17
+ pattern = "lancamentosabc.com.br/track*"
18
+ zone_name = "lancamentosabc.com.br"
19
+
20
+ [[routes]]
21
+ pattern = "*.lancamentosabc.com.br/track*"
22
+ zone_name = "lancamentosabc.com.br"
23
+
6
24
  # ── Variáveis públicas (não são segredos) ─────────────────────────────────────
7
25
  [vars]
8
- META_PIXEL_ID = "1583939052660159"
26
+ META_PIXEL_ID = "SEU_META_PIXEL_ID"
9
27
  GA4_MEASUREMENT_ID = "G-XXXXXXXXXX"
10
28
  TIKTOK_PIXEL_ID = "CXXXXXXXXXXXXXXX"
11
- SITE_DOMAIN = "server-edge-tracker.suporte-ed9.workers.dev"
29
+ SITE_DOMAIN = "SEU_DOMINIO"
12
30
 
13
31
  # ── Banco D1 ──────────────────────────────────────────────────────────────────
14
32
  # Após criar o banco com "wrangler d1 create cdp-edge-db",
@@ -16,7 +34,7 @@ SITE_DOMAIN = "server-edge-tracker.suporte-ed9.workers.dev"
16
34
  [[d1_databases]]
17
35
  binding = "DB"
18
36
  database_name = "cdp-edge-db"
19
- database_id = "7867d38f-5fa8-4c17-b465-386211422c09"
37
+ database_id = "SEU_D1_DATABASE_ID"
20
38
 
21
39
  # ── Queues — Retry + Dead Letter Queue ───────────────────────────────────────
22
40
  # Produtor: worker envia eventos com falha para cdp-edge-retry
@@ -40,8 +58,8 @@ dead_letter_queue = "cdp-edge-dlq"
40
58
  # wrangler kv namespace create GEO_CACHE --preview
41
59
  [[kv_namespaces]]
42
60
  binding = "GEO_CACHE"
43
- id = "821b6c1ccb4b475985439b801c1fdbe0"
44
- preview_id = "d2d9198f47e340ee905a8dc566b09e95"
61
+ id = "SEU_KV_NAMESPACE_ID"
62
+ preview_id = "SEU_KV_NAMESPACE_PREVIEW_ID"
45
63
 
46
64
  # ── R2 Bucket — Audit Logs ────────────────────────────────────────────────────
47
65
  # ⚠️ PENDENTE: Habilitar R2 no Cloudflare Dashboard antes de descomentar