cdp-edge 1.2.2 → 1.4.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 +153 -306
- package/bin/cdp-edge.js +71 -61
- package/contracts/agent-versions.json +682 -0
- package/contracts/api-versions.json +372 -368
- package/contracts/types.ts +81 -0
- package/dist/commands/analyze.js +52 -52
- package/dist/commands/infra.js +54 -54
- package/dist/commands/install.js +26 -3
- package/dist/commands/server.js +174 -174
- package/dist/commands/setup.js +332 -100
- package/dist/commands/validate.js +248 -84
- package/dist/index.js +12 -12
- package/dist/sdk/cdpTrack.js +2095 -0
- package/dist/sdk/cdpTrack.min.js +64 -0
- package/dist/sdk/install-snippet.html +10 -0
- package/docs/whatsapp-ctwa.md +5 -4
- package/extracted-skill/tracking-events-generator/INTEGRACAO-COMPLETA.md +89 -0
- package/extracted-skill/tracking-events-generator/MELHORIAS-IMPLEMENTADAS.md +101 -0
- package/extracted-skill/tracking-events-generator/advanced-matching.js +364 -364
- package/extracted-skill/tracking-events-generator/agents/ab-ltv-agent.md +196 -0
- package/extracted-skill/tracking-events-generator/agents/ab-testing-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/attribution-agent.md +41 -41
- package/extracted-skill/tracking-events-generator/agents/bidding-agent.md +347 -0
- package/extracted-skill/tracking-events-generator/agents/bing-agent.md +40 -50
- package/extracted-skill/tracking-events-generator/agents/browser-tracking.md +174 -74
- package/extracted-skill/tracking-events-generator/agents/code-guardian-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/compliance-agent.md +25 -5
- package/extracted-skill/tracking-events-generator/agents/dashboard-agent.md +10 -10
- package/extracted-skill/tracking-events-generator/agents/database-agent.md +43 -42
- package/extracted-skill/tracking-events-generator/agents/debug-agent.md +22 -22
- package/extracted-skill/tracking-events-generator/agents/devops-agent.md +232 -0
- package/extracted-skill/tracking-events-generator/agents/domain-setup-agent.md +23 -9
- package/extracted-skill/tracking-events-generator/agents/email-agent.md +28 -1
- package/extracted-skill/tracking-events-generator/agents/evo-crm-agent.md +253 -0
- package/extracted-skill/tracking-events-generator/agents/fingerprint-agent.md +206 -1
- package/extracted-skill/tracking-events-generator/agents/fraud-detection-agent.md +143 -0
- package/extracted-skill/tracking-events-generator/agents/google-agent.md +128 -2
- package/extracted-skill/tracking-events-generator/agents/intelligence-agent.md +191 -31
- package/extracted-skill/tracking-events-generator/agents/lead-scoring-agent.md +282 -0
- package/extracted-skill/tracking-events-generator/agents/linkedin-agent.md +145 -34
- package/extracted-skill/tracking-events-generator/agents/localization-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/ltv-predictor-agent.md +24 -5
- package/extracted-skill/tracking-events-generator/agents/master-feedback-loop.md +81 -21
- package/extracted-skill/tracking-events-generator/agents/master-orchestrator.md +588 -93
- package/extracted-skill/tracking-events-generator/agents/match-quality-agent.md +304 -0
- package/extracted-skill/tracking-events-generator/agents/memory-agent.md +190 -15
- package/extracted-skill/tracking-events-generator/agents/meta-agent.md +10 -2
- package/extracted-skill/tracking-events-generator/agents/ml-clustering-agent.md +769 -0
- package/extracted-skill/tracking-events-generator/agents/page-analyzer.md +21 -4
- package/extracted-skill/tracking-events-generator/agents/performance-agent.md +41 -31
- package/extracted-skill/tracking-events-generator/agents/performance-optimization-agent.md +18 -8
- package/extracted-skill/tracking-events-generator/agents/pinterest-agent.md +14 -6
- package/extracted-skill/tracking-events-generator/agents/premium-tracking-intelligence-agent.md +7 -7
- package/extracted-skill/tracking-events-generator/agents/r2-setup-agent.md +16 -8
- package/extracted-skill/tracking-events-generator/agents/reddit-agent.md +15 -7
- package/extracted-skill/tracking-events-generator/agents/security-enterprise-agent.md +157 -48
- package/extracted-skill/tracking-events-generator/agents/server-tracking.md +35 -35
- package/extracted-skill/tracking-events-generator/agents/spotify-agent.md +15 -7
- package/extracted-skill/tracking-events-generator/agents/tiktok-agent.md +73 -2
- package/extracted-skill/tracking-events-generator/agents/tracking-plan-agent.md +104 -9
- package/extracted-skill/tracking-events-generator/agents/utm-agent.md +322 -0
- package/extracted-skill/tracking-events-generator/agents/validator-agent.md +13 -9
- package/extracted-skill/tracking-events-generator/agents/webhook-agent.md +112 -4
- package/extracted-skill/tracking-events-generator/agents/whatsapp-agent.md +58 -5
- package/extracted-skill/tracking-events-generator/agents/whatsapp-ctwa-setup-agent.md +26 -18
- package/extracted-skill/tracking-events-generator/agents/youtube-agent.md +152 -37
- package/extracted-skill/tracking-events-generator/anti-blocking.js +285 -285
- package/extracted-skill/tracking-events-generator/cdpTrack.js +642 -641
- package/extracted-skill/tracking-events-generator/contracts/api-versions.json +14 -10
- package/extracted-skill/tracking-events-generator/engagement-scoring.js +226 -226
- package/extracted-skill/tracking-events-generator/evals/evals.json +235 -235
- package/extracted-skill/tracking-events-generator/integration-test.js +497 -497
- package/extracted-skill/tracking-events-generator/knowledge-base.md +172 -0
- package/extracted-skill/tracking-events-generator/micro-events.js +992 -992
- package/extracted-skill/tracking-events-generator/models/lancamento-imobiliario.md +344 -0
- package/extracted-skill/tracking-events-generator/models/pinterest/conversions-api-template.js +144 -144
- package/extracted-skill/tracking-events-generator/models/pinterest/event-mappings.json +48 -48
- package/extracted-skill/tracking-events-generator/models/pinterest/tag-template.js +28 -28
- package/extracted-skill/tracking-events-generator/models/quiz-funnel.md +83 -19
- package/extracted-skill/tracking-events-generator/models/reddit/conversions-api-template.js +205 -205
- package/extracted-skill/tracking-events-generator/models/reddit/event-mappings.json +56 -56
- package/extracted-skill/tracking-events-generator/models/reddit/pixel-template.js +19 -19
- package/extracted-skill/tracking-events-generator/models/scenarios/behavior-engine.js +425 -425
- package/extracted-skill/tracking-events-generator/route-intent-capture.js +222 -0
- package/extracted-skill/tracking-events-generator/tracking.config.js +3 -3
- package/package.json +89 -75
- package/scripts/build-sdk.js +106 -0
- package/server-edge-tracker/.client.env.example +14 -0
- package/server-edge-tracker/INSTALAR.md +222 -23
- package/server-edge-tracker/SEGMENTATION-DOCS.md +513 -0
- package/server-edge-tracker/config/utm-mapping.json +64 -0
- package/server-edge-tracker/deploy-client.cjs +76 -0
- package/server-edge-tracker/index.ts +1230 -0
- package/server-edge-tracker/migrate-v7.sql +64 -0
- package/server-edge-tracker/modules/db.ts +710 -0
- package/server-edge-tracker/modules/dispatch/crm.ts +382 -0
- package/server-edge-tracker/modules/dispatch/ga4.ts +72 -0
- package/server-edge-tracker/modules/dispatch/meta.ts +143 -0
- package/server-edge-tracker/modules/dispatch/platforms.ts +255 -0
- package/server-edge-tracker/modules/dispatch/tiktok.ts +107 -0
- package/server-edge-tracker/modules/dispatch/whatsapp.ts +296 -0
- package/server-edge-tracker/modules/intelligence.ts +589 -0
- package/server-edge-tracker/modules/ml/bidding.ts +247 -0
- package/server-edge-tracker/modules/ml/fraud.ts +302 -0
- package/server-edge-tracker/modules/ml/logistic.ts +226 -0
- package/server-edge-tracker/modules/ml/ltv.ts +531 -0
- package/server-edge-tracker/modules/ml/matchquality.ts +232 -0
- package/server-edge-tracker/modules/ml/quiz.ts +343 -0
- package/server-edge-tracker/modules/ml/roas.ts +255 -0
- package/server-edge-tracker/modules/ml/segmentation.ts +407 -0
- package/server-edge-tracker/modules/nurture.ts +257 -0
- package/server-edge-tracker/modules/utils.ts +311 -0
- package/server-edge-tracker/modules/utm/utm-enricher.ts +231 -0
- package/server-edge-tracker/schema-ab-ltv.sql +97 -0
- package/server-edge-tracker/schema-bidding.sql +86 -0
- package/server-edge-tracker/schema-fraud.sql +90 -0
- package/server-edge-tracker/schema-indexes.sql +67 -0
- package/server-edge-tracker/schema-ltv-feedback.sql +11 -0
- package/server-edge-tracker/schema-quiz.sql +52 -0
- package/server-edge-tracker/schema-sales-engine.sql +113 -0
- package/server-edge-tracker/schema-segmentation.sql +219 -0
- package/server-edge-tracker/schema-utm.sql +82 -0
- package/server-edge-tracker/schema.sql +281 -265
- package/server-edge-tracker/types.ts +275 -0
- package/server-edge-tracker/wrangler.toml +140 -85
- package/templates/lancamento-imobiliario.md +344 -0
- package/templates/multi-step-checkout.md +3 -4
- package/templates/pinterest/conversions-api-template.js +144 -144
- package/templates/pinterest/event-mappings.json +48 -48
- package/templates/pinterest/tag-template.js +28 -28
- package/templates/quiz-funnel.md +83 -19
- package/templates/reddit/conversions-api-template.js +205 -205
- package/templates/reddit/event-mappings.json +56 -56
- package/templates/reddit/pixel-template.js +12 -39
- package/templates/scenarios/behavior-engine.js +45 -22
- package/docs/PixelBuilder-Documentacao-Completa (2).docx +0 -0
- package/docs/installation.md +0 -155
- package/docs/quick-start.md +0 -185
- package/extracted-skill/tracking-events-generator/agents/crm-integration-agent.md +0 -1419
- package/extracted-skill/tracking-events-generator/agents/intelligence-scheduling.md +0 -643
- package/server-edge-tracker/worker.js +0 -2574
|
@@ -12,6 +12,7 @@ Toda a sua análise deve ser baseada na infraestrutura nativa da Cloudflare.
|
|
|
12
12
|
- Eventos de formulário servem para captura de PII direto para o **D1 Database**.
|
|
13
13
|
- Conversões externas cruzam dados via Webhook + D1.
|
|
14
14
|
- **Human-Behavior Engine**: Micro-eventos são obrigatórios em TODA página.
|
|
15
|
+
- **Worker:** `server-edge-tracker/index.ts` (TypeScript nativo, compilado via wrangler/esbuild)
|
|
15
16
|
|
|
16
17
|
---
|
|
17
18
|
|
|
@@ -24,6 +25,13 @@ Toda a sua análise deve ser baseada na infraestrutura nativa da Cloudflare.
|
|
|
24
25
|
| Botão WhatsApp | `Contact` | 🔴 crítico |
|
|
25
26
|
| Botão "Comprar" → Hotmart/Kiwify/Ticto | `InitiateCheckout` (Trafego Direto) | 🔴 crítico |
|
|
26
27
|
| Página de obrigado | `Purchase_Success` | 🔴 crítico |
|
|
28
|
+
| **Preço Formatado (R$, $, €)** | `value_extraction` (Atrelado ao CTA) | 🔴 crítico |
|
|
29
|
+
| **Campo de Formulário Oculto (CSS hide/opacity 0)** | `honeypot_field` | 🔴 crítico |
|
|
30
|
+
| **[IMÓVEIS] Mapa / botão "Ver localização" / iframe Google Maps** | `FindLocation` | 🔴 crítico imobiliário |
|
|
31
|
+
| **[IMÓVEIS] Simulador de financiamento / parcelas / FGTS / Caixa** | `CustomizeProduct` | 🔴 crítico imobiliário |
|
|
32
|
+
| **[IMÓVEIS] Botão "Favoritar" / ícone de coração / "Salvar imóvel"** | `AddToWishlist` | 🟡 essencial imobiliário |
|
|
33
|
+
| **Aparecimento de Botão Atrasado (Timer)** | `pitch_seen` | 🟡 essencial |
|
|
34
|
+
| **Classe de Erro CSS (.error, .invalid)** | `form_error_detected` | 🟡 essencial |
|
|
27
35
|
| **Micro-Evento: Rage Click** | `rage_click` | 🟡 essencial |
|
|
28
36
|
| **Micro-Evento: Heatmap** | `click_heatmap` (x,y) | 🟡 essencial |
|
|
29
37
|
| **Micro-Evento: Visibility** | `tab_visibility_change` | 🟡 essencial |
|
|
@@ -35,8 +43,9 @@ Toda a sua análise deve ser baseada na infraestrutura nativa da Cloudflare.
|
|
|
35
43
|
Antes de mapear elementos, identifique o **modelo de negócio** da página para ativar protocolos específicos:
|
|
36
44
|
|
|
37
45
|
1. **Lançamento Imobiliário**:
|
|
38
|
-
* Sinais: Galeria de fotos de imóveis, botões WhatsApp, formulário curto, mapas
|
|
39
|
-
* Protocolo: Ativar `geolocation`
|
|
46
|
+
* Sinais: Galeria de fotos de imóveis, botões WhatsApp, formulário curto, mapas, simulador de financiamento, botão favoritar, calendário de agendamento, tour 360°.
|
|
47
|
+
* Protocolo: Ativar `geolocation`, `lead_lock_whatsapp`, `real_estate_events`.
|
|
48
|
+
* Eventos obrigatórios extras: `FindLocation` (mapa/localização), `CustomizeProduct` (simulação financiamento), `AddToWishlist` (favoritar), `Schedule` (agendamento de visita), `Contact` (WhatsApp/telefone), `video_25/50/75/complete` (tour virtual/VSL).
|
|
40
49
|
2. **Página de Vendas (Infoproduto)**:
|
|
41
50
|
* Sinais: Botões Hotmart/Kiwify/Ticto, Vídeo (VSL), Depoimentos, Preço.
|
|
42
51
|
* Protocolo: Ativar `checkout_passthrough` e `vsl_retention`.
|
|
@@ -84,7 +93,9 @@ Retorne APENAS este JSON (sem texto antes ou depois):
|
|
|
84
93
|
"email": "email",
|
|
85
94
|
"nome": "nome-completo",
|
|
86
95
|
"telefone": "telefone",
|
|
87
|
-
"form": "#form-lead"
|
|
96
|
+
"form": "#form-lead",
|
|
97
|
+
"honeypot_detectado": "input[name='website_url_hp']",
|
|
98
|
+
"seletor_erros": ".input-error"
|
|
88
99
|
},
|
|
89
100
|
"evento_sugerido": "Lead",
|
|
90
101
|
"evento_ga4": "generate_lead",
|
|
@@ -99,6 +110,7 @@ Retorne APENAS este JSON (sem texto antes ou depois):
|
|
|
99
110
|
"integracao_externa": "hotmart",
|
|
100
111
|
"evento_sugerido": "InitiateCheckout",
|
|
101
112
|
"seletor_sugerido": "a[href*='hotmart']",
|
|
113
|
+
"valor_extraido": { "seletor": ".price-tag", "moeda": "BRL" },
|
|
102
114
|
"prioridade": "critico"
|
|
103
115
|
},
|
|
104
116
|
{
|
|
@@ -115,7 +127,8 @@ Retorne APENAS este JSON (sem texto antes ou depois):
|
|
|
115
127
|
"tipo": "youtube",
|
|
116
128
|
"id": "dQw4w9WgXcQ",
|
|
117
129
|
"posicao": "hero",
|
|
118
|
-
"evento_sugerido": "ViewContent"
|
|
130
|
+
"evento_sugerido": "ViewContent",
|
|
131
|
+
"pitch_timer_cta": "#btn-compra-atrasado"
|
|
119
132
|
}
|
|
120
133
|
],
|
|
121
134
|
"tem_secao_preco": true,
|
|
@@ -175,6 +188,10 @@ Retorne APENAS este JSON (sem texto antes ou depois):
|
|
|
175
188
|
- Se um arquivo é muito grande (>500 linhas), focar nos primeiros e últimos 100 e nas funções com `submit`, `click`, `form`
|
|
176
189
|
- Se não encontrar nenhum formulário nem CTA relevante em uma página, registrar `tipo_pagina: "generica"` e pular
|
|
177
190
|
- `precisa_server_side: true` quando encontrar integração com Hotmart, Kiwify, Eduzz, Ticto, Stripe, MercadoPago — pois o webhook de compra confirmada precisa do servidor para rastrear Purchase com fbp/fbc
|
|
191
|
+
- **Value Scraping:** Se existir botão de InitiateCheckout/Comprar, busque ativamente por seletor de preço próximo (`.price`, `h2 strong`) para incluir em `valor_extraido`. O Edge precisa do valor exato sem hardcode.
|
|
192
|
+
- **Form Error Tracking:** Mapeie classes CSS de erro (ex: `.error`, `.text-red-500`) em `seletor_erros` para nosso rastreador Edge capturar "taxas de frustração de conversão" orgânicas.
|
|
193
|
+
- **Fraude/Honeypot:** Se houver campos de input ocultos (`display: none`, `opacity: 0`) perto de formulários, marque como `honeypot_detectado`. Robôs preenchem isso; o Fraud Gate Edge usará esse seletor para bloqueio imediato.
|
|
194
|
+
- **Pitch Seen (VSLs):** Procure por botões (CTAs) que iniciam como ocultos (`display: none`) ou são ativados via `setTimeout` em páginas com VSL. Informe em `pitch_timer_cta` para criarmos o evento ultra-qualificado de View Pitch.
|
|
178
195
|
- **A/B test:** quando detectado, `gerar_tracking: true` instrui os agentes de tracking a incluir captura da variante ativa no momento do evento de conversão (Lead, Purchase). A variante é passada em `utmContent` para o Worker e aparece no D1, Meta e GA4 permitindo comparação direta de performance por variante.
|
|
179
196
|
- **Se não houver teste A/B detectado:** omitir o campo `ab_tests` do JSON (não retornar array vazio)
|
|
180
197
|
|
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Performance Agent (Monitoring Master) — CDP Edge
|
|
2
2
|
|
|
3
|
+
> **ESCOPO DESTE AGENTE:** Monitoramento e observabilidade em tempo real.
|
|
4
|
+
> Para otimização de cache, queries e latência, ver: **performance-optimization-agent.md**
|
|
5
|
+
>
|
|
6
|
+
> | Este agente faz | performance-optimization-agent faz |
|
|
7
|
+
> |---|---|
|
|
8
|
+
> | Medir latência, throughput, error rates | Estratégias de caching (L1/L2/L3) |
|
|
9
|
+
> | Alertas de degradação de SLA | Otimização de queries D1 |
|
|
10
|
+
> | Health checks e dashboards | Batch processing, indexação |
|
|
11
|
+
> | Relatórios de performance | Profiling e tunning de Workers |
|
|
12
|
+
|
|
3
13
|
Você é o **Agente de Monitoramento de Performance do CDP Edge**. Sua responsabilidade: **monitorar continuamente a saúde do sistema de tracking** (latência, throughput, error rates, performance de D1) e prover métricas acionáveis para otimização.
|
|
4
14
|
|
|
5
15
|
---
|
|
@@ -26,7 +36,7 @@ Prover **monitoramento contínuo e profissional** da performance do sistema de t
|
|
|
26
36
|
|
|
27
37
|
### 1.1 Latência do Worker
|
|
28
38
|
|
|
29
|
-
```
|
|
39
|
+
```typescript
|
|
30
40
|
// Monitorar tempo de resposta do Cloudflare Worker
|
|
31
41
|
export async function measureWorkerLatency() {
|
|
32
42
|
const sampleSize = 100;
|
|
@@ -105,22 +115,22 @@ function evaluateLatencyPerformance(latencyMetrics) {
|
|
|
105
115
|
|
|
106
116
|
### 1.2 Error Rate das APIs
|
|
107
117
|
|
|
108
|
-
```
|
|
118
|
+
```typescript
|
|
109
119
|
// Monitorar taxa de falhas em todas as APIs
|
|
110
|
-
export async function measureApiErrorRate(hours = 24) {
|
|
120
|
+
export async function measureApiErrorRate(env, hours = 24) {
|
|
111
121
|
const platforms = ['meta', 'google', 'tiktok', 'pinterest', 'reddit'];
|
|
112
122
|
const errorRates = {};
|
|
113
123
|
|
|
114
124
|
for (const platform of platforms) {
|
|
115
125
|
// Total de requisições (sucesso + falha)
|
|
116
|
-
const totalRequests = await DB.prepare(`
|
|
126
|
+
const totalRequests = await env.DB.prepare(`
|
|
117
127
|
SELECT COUNT(*) as total
|
|
118
128
|
FROM events_log
|
|
119
129
|
WHERE platform = ? AND created_at > datetime('now', '-${hours} hours')
|
|
120
130
|
`).bind(platform).get();
|
|
121
131
|
|
|
122
132
|
// Requisições que falharam
|
|
123
|
-
const failedRequests = await DB.prepare(`
|
|
133
|
+
const failedRequests = await env.DB.prepare(`
|
|
124
134
|
SELECT COUNT(*) as failed
|
|
125
135
|
FROM events_log
|
|
126
136
|
WHERE platform = ? AND status = 'failed' AND created_at > datetime('now', '-${hours} hours')
|
|
@@ -157,9 +167,9 @@ function evaluateErrorRate(errorRate) {
|
|
|
157
167
|
|
|
158
168
|
### 1.3 Throughput do Sistema
|
|
159
169
|
|
|
160
|
-
```
|
|
170
|
+
```typescript
|
|
161
171
|
// Monitorar eventos processados por segundo/minuto
|
|
162
|
-
export async function measureThroughput(hours = 24) {
|
|
172
|
+
export async function measureThroughput(env, hours = 24) {
|
|
163
173
|
const now = new Date();
|
|
164
174
|
const windows = [];
|
|
165
175
|
|
|
@@ -168,7 +178,7 @@ export async function measureThroughput(hours = 24) {
|
|
|
168
178
|
const windowStart = new Date(now - (i + 1) * 60 * 60 * 1000);
|
|
169
179
|
const windowEnd = new Date(now - i * 60 * 60 * 1000);
|
|
170
180
|
|
|
171
|
-
const eventsInWindow = await DB.prepare(`
|
|
181
|
+
const eventsInWindow = await env.DB.prepare(`
|
|
172
182
|
SELECT COUNT(*) as events,
|
|
173
183
|
MIN(created_at) as first_event,
|
|
174
184
|
MAX(created_at) as last_event
|
|
@@ -227,11 +237,11 @@ function evaluateThroughputTrend(recent, historical) {
|
|
|
227
237
|
|
|
228
238
|
### 1.4 Performance de D1
|
|
229
239
|
|
|
230
|
-
```
|
|
240
|
+
```typescript
|
|
231
241
|
// Monitorar performance do banco de dados D1
|
|
232
|
-
export async function measureD1Performance(hours = 24) {
|
|
242
|
+
export async function measureD1Performance(env, hours = 24) {
|
|
233
243
|
// Queries lentas
|
|
234
|
-
const slowQueries = await DB.prepare(`
|
|
244
|
+
const slowQueries = await env.DB.prepare(`
|
|
235
245
|
SELECT
|
|
236
246
|
query_hash,
|
|
237
247
|
COUNT(*) as execution_count,
|
|
@@ -246,7 +256,7 @@ export async function measureD1Performance(hours = 24) {
|
|
|
246
256
|
`).all();
|
|
247
257
|
|
|
248
258
|
// Verificar locks
|
|
249
|
-
const locks = await DB.prepare(`
|
|
259
|
+
const locks = await env.DB.prepare(`
|
|
250
260
|
SELECT
|
|
251
261
|
COUNT(*) as total_locks,
|
|
252
262
|
AVG(lock_duration_ms) as avg_lock_duration,
|
|
@@ -321,11 +331,11 @@ function evaluateD1Health(slowQueries, locks, dbSize) {
|
|
|
321
331
|
|
|
322
332
|
### 1.5 Cache Performance (KV)
|
|
323
333
|
|
|
324
|
-
```
|
|
334
|
+
```typescript
|
|
325
335
|
// Monitorar eficiência do cache KV
|
|
326
|
-
export async function measureCachePerformance(hours = 24) {
|
|
336
|
+
export async function measureCachePerformance(env, hours = 24) {
|
|
327
337
|
// Cache hits e misses
|
|
328
|
-
const cacheStats = await DB.prepare(`
|
|
338
|
+
const cacheStats = await env.DB.prepare(`
|
|
329
339
|
SELECT
|
|
330
340
|
COUNT(*) FILTER (WHERE hit = 1) as hits,
|
|
331
341
|
COUNT(*) FILTER (WHERE hit = 0) as misses,
|
|
@@ -340,7 +350,7 @@ export async function measureCachePerformance(hours = 24) {
|
|
|
340
350
|
const hitRate = total > 0 ? (hits / total * 100) : 0;
|
|
341
351
|
|
|
342
352
|
// Keys armazenadas
|
|
343
|
-
const totalKeys = await
|
|
353
|
+
const totalKeys = await env.GEO_CACHE.list().then(list => list.keys.length);
|
|
344
354
|
|
|
345
355
|
return {
|
|
346
356
|
hits,
|
|
@@ -539,7 +549,7 @@ alerts:
|
|
|
539
549
|
|
|
540
550
|
### Implementação com Server-Sent Events (SSE)
|
|
541
551
|
|
|
542
|
-
```
|
|
552
|
+
```typescript
|
|
543
553
|
// Endpoint SSE para atualizações em tempo real do dashboard
|
|
544
554
|
export async function handleMonitoringStream(request, env) {
|
|
545
555
|
const headers = {
|
|
@@ -846,10 +856,10 @@ cpu_ms = 50 # Aumentar de 10ms para 50ms
|
|
|
846
856
|
**Problema:** Queries repetidas ao D1 degradam performance.
|
|
847
857
|
|
|
848
858
|
**Solução:**
|
|
849
|
-
```
|
|
859
|
+
```typescript
|
|
850
860
|
// Cache de métricas globais por 1 hora
|
|
851
861
|
const cacheKey = `metrics:global:${getHourBucket()}`;
|
|
852
|
-
const cached = await
|
|
862
|
+
const cached = await env.GEO_CACHE.get(cacheKey);
|
|
853
863
|
|
|
854
864
|
if (cached) {
|
|
855
865
|
return JSON.parse(cached);
|
|
@@ -857,7 +867,7 @@ if (cached) {
|
|
|
857
867
|
|
|
858
868
|
// Cache miss — consultar D1 e persistir no KV
|
|
859
869
|
const metrics = await fetchMetricsFromD1();
|
|
860
|
-
await
|
|
870
|
+
await env.GEO_CACHE.put(cacheKey, JSON.stringify(metrics), { expirationTtl: 3600 });
|
|
861
871
|
|
|
862
872
|
return metrics;
|
|
863
873
|
```
|
|
@@ -871,7 +881,7 @@ return metrics;
|
|
|
871
881
|
**Problema:** Processar eventos um por um é ineficiente.
|
|
872
882
|
|
|
873
883
|
**Solução:**
|
|
874
|
-
```
|
|
884
|
+
```typescript
|
|
875
885
|
// Agrupar eventos em batches de 10
|
|
876
886
|
const eventBatches = [];
|
|
877
887
|
for (let i = 0; i < events.length; i += 10) {
|
|
@@ -940,7 +950,7 @@ WHERE e.created_at > datetime('now', '-1 day')
|
|
|
940
950
|
**Problema:** Enviar eventos muito rápido causa 429 errors.
|
|
941
951
|
|
|
942
952
|
**Solução:**
|
|
943
|
-
```
|
|
953
|
+
```typescript
|
|
944
954
|
// Rate limiting com token bucket algorithm
|
|
945
955
|
const RATE_LIMITS = {
|
|
946
956
|
meta: { tokens: 200, refill_rate: 10 }, // 200 req/min, recarrega 10/min
|
|
@@ -948,17 +958,17 @@ const RATE_LIMITS = {
|
|
|
948
958
|
tiktok: { tokens: 10, refill_rate: 1 } // 10 req/min
|
|
949
959
|
};
|
|
950
960
|
|
|
951
|
-
async function consumeToken(platform) {
|
|
961
|
+
async function consumeToken(platform, env) {
|
|
952
962
|
const limit = RATE_LIMITS[platform];
|
|
953
963
|
const key = `rate_limit:${platform}`;
|
|
954
964
|
|
|
955
|
-
let tokens = await
|
|
965
|
+
let tokens = await env.GEO_CACHE.get(key) || JSON.stringify(limit.tokens);
|
|
956
966
|
|
|
957
967
|
tokens = JSON.parse(tokens);
|
|
958
968
|
|
|
959
969
|
if (tokens > 0) {
|
|
960
970
|
tokens--;
|
|
961
|
-
await
|
|
971
|
+
await env.GEO_CACHE.put(key, JSON.stringify(tokens));
|
|
962
972
|
return true; // Permitido
|
|
963
973
|
}
|
|
964
974
|
|
|
@@ -975,7 +985,7 @@ async function consumeToken(platform) {
|
|
|
975
985
|
**Problema:** Perda de eventos durante rate limits.
|
|
976
986
|
|
|
977
987
|
**Solução:**
|
|
978
|
-
```
|
|
988
|
+
```typescript
|
|
979
989
|
// Cloudflare Queue para eventos bloqueados
|
|
980
990
|
export async function queueEventForRetry(event, platform, reason) {
|
|
981
991
|
await QUEUE.send('cdp-edge-events', {
|
|
@@ -1008,7 +1018,7 @@ setInterval(async () => {
|
|
|
1008
1018
|
**Problema:** TTL muito baixo causa cache misses frequentes.
|
|
1009
1019
|
|
|
1010
1020
|
**Solução:**
|
|
1011
|
-
```
|
|
1021
|
+
```typescript
|
|
1012
1022
|
// TTLs otimizados por tipo de dado
|
|
1013
1023
|
const CACHE_TTL = {
|
|
1014
1024
|
metrics_global: 3600, // 1 hora para métricas globais
|
|
@@ -1028,19 +1038,19 @@ const CACHE_TTL = {
|
|
|
1028
1038
|
**Problema:** Cache desatualizado causa dados incorretos.
|
|
1029
1039
|
|
|
1030
1040
|
**Solução:**
|
|
1031
|
-
```
|
|
1041
|
+
```typescript
|
|
1032
1042
|
// Invalidar cache quando dados mudarem
|
|
1033
|
-
async function invalidateCacheOnChange(eventType) {
|
|
1043
|
+
async function invalidateCacheOnChange(eventType, env) {
|
|
1034
1044
|
const patterns = {
|
|
1035
1045
|
'lead_created': ['metrics:*', 'user_profile:*'],
|
|
1036
1046
|
'purchase_completed': ['metrics:*', 'session_data:*'],
|
|
1037
1047
|
'api_config_changed': ['api_config:*']
|
|
1038
1048
|
};
|
|
1039
1049
|
|
|
1040
|
-
const keysToDelete = await
|
|
1050
|
+
const keysToDelete = await env.GEO_CACHE.list({ prefix: patterns[eventType] });
|
|
1041
1051
|
|
|
1042
1052
|
for (const key of keysToDelete.keys) {
|
|
1043
|
-
await
|
|
1053
|
+
await env.GEO_CACHE.delete(key.name);
|
|
1044
1054
|
}
|
|
1045
1055
|
|
|
1046
1056
|
console.log(`Invalidated ${keysToDelete.keys.length} cache keys for ${eventType}`);
|
|
@@ -8,6 +8,16 @@ version: "1.0.0"
|
|
|
8
8
|
|
|
9
9
|
# Performance Optimization Enterprise Agent
|
|
10
10
|
|
|
11
|
+
> **ESCOPO DESTE AGENTE:** Otimização ativa de performance — caching, queries, batching.
|
|
12
|
+
> Para monitoramento passivo (métricas, alertas, dashboards), ver: **performance-agent.md**
|
|
13
|
+
>
|
|
14
|
+
> | Este agente faz | performance-agent faz |
|
|
15
|
+
> |---|---|
|
|
16
|
+
> | Estratégias de caching L1/L2/L3 | Medir latência e throughput |
|
|
17
|
+
> | Otimização de queries D1 e indexação | Alertas de degradação de SLA |
|
|
18
|
+
> | Batch processing e pipeline tuning | Health checks e dashboards |
|
|
19
|
+
> | Profiling de Workers e CPU optimization | Relatórios de performance |
|
|
20
|
+
|
|
11
21
|
## 🚀 Visão Geral
|
|
12
22
|
|
|
13
23
|
Agente especializado em otimização de performance para o sistema CDP Edge (Cloudflare Workers + D1 + Queue). Implementa estratégias de caching multi-camada, otimização de queries, processamento em lote e monitoramento de latência em tempo real.
|
|
@@ -65,7 +75,7 @@ Agente especializado em otimização de performance para o sistema CDP Edge (Clo
|
|
|
65
75
|
|
|
66
76
|
### L1: Memory Cache (Request-Scoped)
|
|
67
77
|
|
|
68
|
-
```
|
|
78
|
+
```typescript
|
|
69
79
|
/**
|
|
70
80
|
* L1 Memory Cache - In-request cache with automatic expiration
|
|
71
81
|
*/
|
|
@@ -153,13 +163,13 @@ let l1Cache = new L1Cache();
|
|
|
153
163
|
|
|
154
164
|
### L2: KV Cache (Global Edge Cache)
|
|
155
165
|
|
|
156
|
-
```
|
|
166
|
+
```typescript
|
|
157
167
|
/**
|
|
158
168
|
* L2 KV Cache - Global distributed cache with automatic invalidation
|
|
159
169
|
*/
|
|
160
170
|
class L2Cache {
|
|
161
171
|
constructor(env) {
|
|
162
|
-
this.kv = env.
|
|
172
|
+
this.kv = env.GEO_CACHE; // Cloudflare KV namespace
|
|
163
173
|
this.stats = {
|
|
164
174
|
hits: 0,
|
|
165
175
|
misses: 0,
|
|
@@ -304,7 +314,7 @@ let l2Cache = null;
|
|
|
304
314
|
|
|
305
315
|
### Cache Strategy Implementation
|
|
306
316
|
|
|
307
|
-
```
|
|
317
|
+
```typescript
|
|
308
318
|
/**
|
|
309
319
|
* Multi-Layer Cache Manager
|
|
310
320
|
* Orchestrates L1 and L2 caches with fallback logic
|
|
@@ -475,7 +485,7 @@ CREATE INDEX IF NOT EXISTS idx_channel_performance_updated
|
|
|
475
485
|
|
|
476
486
|
### Query Optimization Patterns
|
|
477
487
|
|
|
478
|
-
```
|
|
488
|
+
```typescript
|
|
479
489
|
/**
|
|
480
490
|
* Optimized Query Builder for D1
|
|
481
491
|
*/
|
|
@@ -666,7 +676,7 @@ let queryOptimizer = null;
|
|
|
666
676
|
|
|
667
677
|
### Batch Processing for Attribution
|
|
668
678
|
|
|
669
|
-
```
|
|
679
|
+
```typescript
|
|
670
680
|
/**
|
|
671
681
|
* Batch Attribution Processor
|
|
672
682
|
* Processes multiple attributions in parallel with batching
|
|
@@ -928,7 +938,7 @@ let batchProcessor = null;
|
|
|
928
938
|
|
|
929
939
|
### Performance Monitoring
|
|
930
940
|
|
|
931
|
-
```
|
|
941
|
+
```typescript
|
|
932
942
|
/**
|
|
933
943
|
* Latency Profiler
|
|
934
944
|
* Monitors and tracks performance metrics
|
|
@@ -1199,7 +1209,7 @@ let latencyProfiler = new LatencyProfiler();
|
|
|
1199
1209
|
|
|
1200
1210
|
### Worker API Endpoints
|
|
1201
1211
|
|
|
1202
|
-
```
|
|
1212
|
+
```typescript
|
|
1203
1213
|
/**
|
|
1204
1214
|
* Performance Monitoring Endpoints
|
|
1205
1215
|
*/
|
|
@@ -7,6 +7,14 @@ Você não gera código para outras plataformas. Foco total em Pinterest.
|
|
|
7
7
|
|
|
8
8
|
---
|
|
9
9
|
|
|
10
|
+
## ✅ REGRAS CRÍTICAS
|
|
11
|
+
|
|
12
|
+
0. **CONSULTA OBRIGATÓRIA À MEMÓRIA**: Extraia o ID de Tag Pinterest, Token de Acesso e ID de Conta de Anúncios (`PINTEREST_TAG_ID`, `PINTEREST_ACCESS_TOKEN`, `PINTEREST_AD_ACCOUNT_ID`) consultando ativamente o "memory-agent.json". Solicite ao Orquestrador tudo o que faltar. Execute integrações exclusivamente com os dados oficiais guardados na Memória para garantir alinhamento sistêmico.
|
|
13
|
+
1. Cloudflare-Only: Sem dependências externas.
|
|
14
|
+
2. Same-Domain: Worker no domínio do site (anti-adblock).
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
10
18
|
## ACESSO À BASE DE CONHECIMENTO E DOCUMENTAÇÃO EXTERNA
|
|
11
19
|
|
|
12
20
|
### PASSO 0 obrigatório — ler ANTES de gerar qualquer código
|
|
@@ -26,7 +34,7 @@ Buscar: "Pinterest", "pintrk", "pin_id", "Pinterest Conversions API", "PINTEREST
|
|
|
26
34
|
|
|
27
35
|
### PASSO 0 obrigatório — Ler Versões de API (api-versions.json)
|
|
28
36
|
|
|
29
|
-
```
|
|
37
|
+
```typescript
|
|
30
38
|
// Ler versões do arquivo centralizado
|
|
31
39
|
const apiVersions = await readJSON('contracts/api-versions.json');
|
|
32
40
|
const pinterestVersion = apiVersions.pinterest;
|
|
@@ -78,7 +86,7 @@ if (isDeprecated) {
|
|
|
78
86
|
|
|
79
87
|
**Ler do template:** `models/pinterest/tag-template.js`
|
|
80
88
|
|
|
81
|
-
```
|
|
89
|
+
```typescript
|
|
82
90
|
import { PINTEREST_TAG_TEMPLATE } from '../models/pinterest/tag-template.js';
|
|
83
91
|
|
|
84
92
|
// Substituir placeholders
|
|
@@ -185,7 +193,7 @@ Seu código gerado será incorporado pelo **Browser Tracking Agent** e **Server
|
|
|
185
193
|
[Função de inicialização + pintrk('load') + pintrk('page')]
|
|
186
194
|
|
|
187
195
|
### PINTEREST_CONVERSIONS_API_FUNCTION
|
|
188
|
-
[função sendPinterestApi() para o
|
|
196
|
+
[função sendPinterestApi() para o index.ts]
|
|
189
197
|
|
|
190
198
|
### PINTEREST_HEAD_TAGS
|
|
191
199
|
[tags <script> e <noscript> para inserir no <head>]
|
|
@@ -197,7 +205,7 @@ Seu código gerado será incorporado pelo **Browser Tracking Agent** e **Server
|
|
|
197
205
|
[Referência ao models/pinterest/event-mappings.json]
|
|
198
206
|
```
|
|
199
207
|
|
|
200
|
-
O Master Orchestrator usará esses blocos para injetar no `tracking.js` e `
|
|
208
|
+
O Master Orchestrator usará esses blocos para injetar no `tracking.js` e `index.ts` via Write/Edit.
|
|
201
209
|
|
|
202
210
|
---
|
|
203
211
|
|
|
@@ -246,7 +254,7 @@ wrangler secret put PINTEREST_AD_ACCOUNT_ID --name server-edge-tracker
|
|
|
246
254
|
Quando o Master Orchestrator solicitar código do Pinterest Agent:
|
|
247
255
|
|
|
248
256
|
1. **Ler versões da API:**
|
|
249
|
-
```
|
|
257
|
+
```typescript
|
|
250
258
|
const apiVersions = await readJSON('contracts/api-versions.json');
|
|
251
259
|
const pinterestVersion = apiVersions.pinterest.conversions_api.current; // "v5"
|
|
252
260
|
```
|
|
@@ -294,7 +302,7 @@ Quando o Master Orchestrator solicitar código do Pinterest Agent:
|
|
|
294
302
|
{
|
|
295
303
|
"blocos_gerados": {
|
|
296
304
|
"PINTEREST_BROWSER_SNIPPET": "pintrk('load') + pintrk('page') + eventos",
|
|
297
|
-
"PINTEREST_CONVERSIONS_API_FUNCTION": "sendPinterestApi() para
|
|
305
|
+
"PINTEREST_CONVERSIONS_API_FUNCTION": "sendPinterestApi() para index.ts",
|
|
298
306
|
"PINTEREST_HEAD_TAGS": "<script> + <noscript> para <head>",
|
|
299
307
|
"PINTEREST_CSP_DOMAINS": ["ct.pinterest.com", "log.pinterest.com"]
|
|
300
308
|
},
|
package/extracted-skill/tracking-events-generator/agents/premium-tracking-intelligence-agent.md
CHANGED
|
@@ -553,7 +553,7 @@ function detectAdBlock() {
|
|
|
553
553
|
function handleAdBlockFallback(eventData) {
|
|
554
554
|
if (detectAdBlock()) {
|
|
555
555
|
// AdBlock ativo: enviar via servidor (não pode usar scripts de terceiros)
|
|
556
|
-
fetch('/
|
|
556
|
+
fetch('/track', {
|
|
557
557
|
method: 'POST',
|
|
558
558
|
headers: { 'Content-Type': 'application/json' },
|
|
559
559
|
body: JSON.stringify({
|
|
@@ -619,9 +619,9 @@ function getSessionId() {
|
|
|
619
619
|
```javascript
|
|
620
620
|
/**
|
|
621
621
|
* Endpoint de Tracking no Mesmo Domínio
|
|
622
|
-
* URL: https://meusite.com/
|
|
622
|
+
* URL: https://meusite.com/track (NÃO third-party)
|
|
623
623
|
*/
|
|
624
|
-
const TRACKING_ENDPOINT = '/
|
|
624
|
+
const TRACKING_ENDPOINT = '/track'; // Same-Domain Protocol
|
|
625
625
|
|
|
626
626
|
/**
|
|
627
627
|
* Enviar evento via servidor (adblock-proof)
|
|
@@ -711,10 +711,10 @@ const browserTracking = {
|
|
|
711
711
|
};
|
|
712
712
|
```
|
|
713
713
|
|
|
714
|
-
### O que roda no Servidor (Cloudflare Worker)
|
|
714
|
+
### O que roda no Servidor (Cloudflare Worker — TypeScript)
|
|
715
715
|
|
|
716
|
-
```
|
|
717
|
-
// Server Tracking - Processamento e despacho para plataformas
|
|
716
|
+
```typescript
|
|
717
|
+
// Server Tracking - Processamento e despacho para plataformas (index.ts)
|
|
718
718
|
const serverTracking = {
|
|
719
719
|
// 1. Receber evento do browser
|
|
720
720
|
handleEvent: async (eventData, env, ctx) => {
|
|
@@ -804,7 +804,7 @@ const serverTracking = {
|
|
|
804
804
|
|
|
805
805
|
### Server Tracking (O que processar no Worker)
|
|
806
806
|
|
|
807
|
-
- [x] Receber eventos do browser (POST /
|
|
807
|
+
- [x] Receber eventos do browser (POST /track)
|
|
808
808
|
- [x] Capturar IP e geolocalização (Cloudflare headers)
|
|
809
809
|
- [x] Recuperar PII do D1 (Lead Lock)
|
|
810
810
|
- [x] Calcular Engagement Score (0.0 - 5.0)
|
|
@@ -7,6 +7,14 @@
|
|
|
7
7
|
|
|
8
8
|
---
|
|
9
9
|
|
|
10
|
+
## ✅ REGRAS CRÍTICAS
|
|
11
|
+
|
|
12
|
+
0. **CONSULTA OBRIGATÓRIA À MEMÓRIA**: Extraia o Nome do Bucket R2 e IDs de Conta Cloudflare (`R2_BUCKET_NAME`, `CF_ACCOUNT_ID`) consultando ativamente o "memory-agent.json". Solicite ao Orquestrador tudo o que faltar. Execute configurações de storage exclusivamente com os dados oficiais guardados na Memória para garantir alinhamento sistêmico.
|
|
13
|
+
1. Cloudflare-Only: Sem dependências externas.
|
|
14
|
+
2. Same-Domain: Worker no domínio do site (anti-adblock).
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
10
18
|
## Por que o R2 é necessário
|
|
11
19
|
|
|
12
20
|
| Sem R2 | Com R2 |
|
|
@@ -103,13 +111,13 @@ bucket_name = "cdp-edge-logs"
|
|
|
103
111
|
|
|
104
112
|
---
|
|
105
113
|
|
|
106
|
-
## Fase 4 — Ativar saveAuditLog() no
|
|
114
|
+
## Fase 4 — Ativar saveAuditLog() no index.ts
|
|
107
115
|
|
|
108
|
-
O
|
|
116
|
+
O index.ts já possui a função `saveAuditLog()` implementada mas com o binding condicional. Após descomentar o binding, ela passa a salvar automaticamente.
|
|
109
117
|
|
|
110
|
-
### Verificar a função no
|
|
118
|
+
### Verificar a função no index.ts:
|
|
111
119
|
|
|
112
|
-
```
|
|
120
|
+
```typescript
|
|
113
121
|
// Buscar por: saveAuditLog ou AUDIT_LOGS
|
|
114
122
|
async function saveAuditLog(env, eventId, eventType, payload, platforms) {
|
|
115
123
|
if (!env.AUDIT_LOGS) return; // Skip se R2 não configurado (graceful degradation)
|
|
@@ -131,9 +139,9 @@ async function saveAuditLog(env, eventId, eventType, payload, platforms) {
|
|
|
131
139
|
}
|
|
132
140
|
```
|
|
133
141
|
|
|
134
|
-
Se a função não existir ainda, adicionar ao
|
|
142
|
+
Se a função não existir ainda, adicionar ao index.ts (seção de funções utilitárias):
|
|
135
143
|
|
|
136
|
-
```
|
|
144
|
+
```typescript
|
|
137
145
|
// ── R2 Audit Log ─────────────────────────────────────────────────────────────
|
|
138
146
|
async function saveAuditLog(env, eventId, eventType, payload, platforms) {
|
|
139
147
|
if (!env.AUDIT_LOGS) return;
|
|
@@ -153,7 +161,7 @@ async function saveAuditLog(env, eventId, eventType, payload, platforms) {
|
|
|
153
161
|
|
|
154
162
|
Adicionar ao `Promise.allSettled` no endpoint `/track` (dentro de `ctx.waitUntil`):
|
|
155
163
|
|
|
156
|
-
```
|
|
164
|
+
```typescript
|
|
157
165
|
// Adicionar como última entrada no allSettled:
|
|
158
166
|
saveAuditLog(env, eventId, eventType, payload, ['meta', 'ga4', 'tiktok']),
|
|
159
167
|
```
|
|
@@ -218,7 +226,7 @@ R2 Dashboard
|
|
|
218
226
|
[ ] R2 habilitado no Cloudflare Dashboard
|
|
219
227
|
[ ] Bucket cdp-edge-logs criado
|
|
220
228
|
[ ] wrangler.toml: [[r2_buckets]] descomentado
|
|
221
|
-
[ ]
|
|
229
|
+
[ ] index.ts: saveAuditLog() implementada
|
|
222
230
|
[ ] wrangler deploy executado sem erros
|
|
223
231
|
[ ] Evento de teste disparado
|
|
224
232
|
[ ] Objeto .json visível no R2 Dashboard
|
|
@@ -7,6 +7,14 @@ Você não gera código para outras plataformas. Foco total em Reddit.
|
|
|
7
7
|
|
|
8
8
|
---
|
|
9
9
|
|
|
10
|
+
## ✅ REGRAS CRÍTICAS
|
|
11
|
+
|
|
12
|
+
0. **CONSULTA OBRIGATÓRIA À MEMÓRIA**: Extraia o ID de Pixel Reddit, Token de Acesso e ID de Conta de Anúncios (`REDDIT_PIXEL_ID`, `REDDIT_ACCESS_TOKEN`, `REDDIT_AD_ACCOUNT_ID`) consultando ativamente o "memory-agent.json". Solicite ao Orquestrador tudo o que faltar. Execute integrações exclusivamente com os dados oficiais guardados na Memória para garantir alinhamento sistêmico.
|
|
13
|
+
1. Cloudflare-Only: Sem dependências externas.
|
|
14
|
+
2. Same-Domain: Worker no domínio do site (anti-adblock).
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
10
18
|
## ACESSO À BASE DE CONHECIMENTO E DOCUMENTAÇÃO EXTERNA
|
|
11
19
|
|
|
12
20
|
### PASSO 0 obrigatório — ler ANTES de gerar qualquer código
|
|
@@ -28,7 +36,7 @@ Buscar: "Reddit", "reddit pixel", "rdt", "Reddit Conversions API"
|
|
|
28
36
|
|
|
29
37
|
### PASSO 0 obrigatório — Ler Versões de API (api-versions.json)
|
|
30
38
|
|
|
31
|
-
```
|
|
39
|
+
```typescript
|
|
32
40
|
// Ler versões do arquivo centralizado
|
|
33
41
|
const apiVersions = await readJSON('contracts/api-versions.json');
|
|
34
42
|
const redditVersion = apiVersions.reddit;
|
|
@@ -78,7 +86,7 @@ if (isDeprecated) {
|
|
|
78
86
|
|
|
79
87
|
**Ler do template:** `models/reddit/pixel-template.js`
|
|
80
88
|
|
|
81
|
-
```
|
|
89
|
+
```typescript
|
|
82
90
|
import { REDDIT_PIXEL_TEMPLATE } from '../models/reddit/pixel-template.js';
|
|
83
91
|
|
|
84
92
|
// Substituir placeholders
|
|
@@ -144,7 +152,7 @@ function reinitRedditWithUserData(userData) {
|
|
|
144
152
|
|
|
145
153
|
**Ler do template:** `models/reddit/conversions-api-template.js`
|
|
146
154
|
|
|
147
|
-
```
|
|
155
|
+
```typescript
|
|
148
156
|
// Reutilizar funções do template
|
|
149
157
|
import {
|
|
150
158
|
trackRedditLead,
|
|
@@ -232,13 +240,13 @@ Seu código gerado (Reddit Pixel browser + Conversions API server) será incorpo
|
|
|
232
240
|
[rdt('init') + rdt('track', 'PageVisit') + funções de evento browser]
|
|
233
241
|
|
|
234
242
|
### REDDIT_CONVERSIONS_FUNCTION
|
|
235
|
-
[função sendRedditApi() para o
|
|
243
|
+
[função sendRedditApi() para o index.ts]
|
|
236
244
|
|
|
237
245
|
### REDDIT_HEAD_TAGS
|
|
238
246
|
[tag <script> para inserir no <head>]
|
|
239
247
|
```
|
|
240
248
|
|
|
241
|
-
O Master Orchestrator usará esses blocos para injetar no `tracking.js` e `
|
|
249
|
+
O Master Orchestrator usará esses blocos para injetar no `tracking.js` e `index.ts` via Write/Edit.
|
|
242
250
|
|
|
243
251
|
---
|
|
244
252
|
|
|
@@ -247,7 +255,7 @@ O Master Orchestrator usará esses blocos para injetar no `tracking.js` e `worke
|
|
|
247
255
|
Quando o Master Orchestrator solicitar código do Reddit Agent:
|
|
248
256
|
|
|
249
257
|
1. **Ler versões da API:**
|
|
250
|
-
```
|
|
258
|
+
```typescript
|
|
251
259
|
const apiVersions = await readJSON('contracts/api-versions.json');
|
|
252
260
|
const redditVersion = apiVersions.reddit.conversions_api.current; // "v2.0"
|
|
253
261
|
```
|
|
@@ -297,7 +305,7 @@ Quando o Master Orchestrator solicitar código do Reddit Agent:
|
|
|
297
305
|
{
|
|
298
306
|
"blocos_gerados": {
|
|
299
307
|
"REDDIT_BROWSER_SNIPPET": "rdt('init') + rdt('track', 'PageVisit') + eventos",
|
|
300
|
-
"REDDIT_CONVERSIONS_FUNCTION": "sendRedditApi() para
|
|
308
|
+
"REDDIT_CONVERSIONS_FUNCTION": "sendRedditApi() para index.ts",
|
|
301
309
|
"REDDIT_HEAD_TAGS": "<script> para <head>"
|
|
302
310
|
},
|
|
303
311
|
"versao_api": "v2.0",
|