cdp-edge 1.18.0 → 2.0.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.
Files changed (34) hide show
  1. package/README.md +308 -308
  2. package/bin/cdp-edge.js +61 -61
  3. package/dist/commands/analyze.js +52 -52
  4. package/dist/commands/infra.js +54 -54
  5. package/dist/commands/install.js +187 -0
  6. package/dist/commands/server.js +174 -174
  7. package/dist/commands/setup.js +19 -1
  8. package/dist/commands/validate.js +84 -84
  9. package/dist/index.js +12 -12
  10. package/extracted-skill/tracking-events-generator/advanced-matching.js +364 -364
  11. package/extracted-skill/tracking-events-generator/anti-blocking.js +285 -285
  12. package/extracted-skill/tracking-events-generator/cdpTrack.js +641 -641
  13. package/extracted-skill/tracking-events-generator/engagement-scoring.js +226 -226
  14. package/extracted-skill/tracking-events-generator/evals/evals.json +235 -235
  15. package/extracted-skill/tracking-events-generator/integration-test.js +497 -497
  16. package/extracted-skill/tracking-events-generator/micro-events.js +992 -992
  17. package/extracted-skill/tracking-events-generator/models/pinterest/conversions-api-template.js +144 -144
  18. package/extracted-skill/tracking-events-generator/models/pinterest/event-mappings.json +48 -48
  19. package/extracted-skill/tracking-events-generator/models/pinterest/tag-template.js +28 -28
  20. package/extracted-skill/tracking-events-generator/models/reddit/conversions-api-template.js +205 -205
  21. package/extracted-skill/tracking-events-generator/models/reddit/event-mappings.json +56 -56
  22. package/extracted-skill/tracking-events-generator/models/reddit/pixel-template.js +19 -19
  23. package/extracted-skill/tracking-events-generator/models/scenarios/behavior-engine.js +425 -425
  24. package/package.json +76 -76
  25. package/server-edge-tracker/schema.sql +265 -265
  26. package/server-edge-tracker/worker.js +4160 -4160
  27. package/server-edge-tracker/wrangler.toml +103 -103
  28. package/templates/pinterest/conversions-api-template.js +144 -144
  29. package/templates/pinterest/event-mappings.json +48 -48
  30. package/templates/pinterest/tag-template.js +28 -28
  31. package/templates/reddit/conversions-api-template.js +205 -205
  32. package/templates/reddit/event-mappings.json +56 -56
  33. package/templates/reddit/pixel-template.js +19 -19
  34. package/templates/scenarios/behavior-engine.js +425 -425
@@ -1,174 +1,174 @@
1
- /**
2
- * Server Command - Infraestrutura Cloudflare Workers
3
- */
4
-
5
- import chalk from 'chalk';
6
- import ora from 'ora';
7
- import { promises as fs } from 'fs';
8
- import { join } from 'path';
9
-
10
- export async function runServer(dir) {
11
- console.log(chalk.cyan.bold('\n CDP Edge - Server-Side Tracking\n'));
12
-
13
- const spinner = ora('Gerando infraestrutura...').start();
14
-
15
- try {
16
- // Gerar worker.js
17
- await generateWorker(dir);
18
-
19
- // Gerar schema.sql
20
- await generateSchema(dir);
21
-
22
- // Gerar wrangler.toml
23
- await generateWranglerConfig(dir);
24
-
25
- spinner.succeed(chalk.green('Infraestrutura gerada!'));
26
-
27
- console.log('\n' + chalk.yellow('Arquivos gerados:'));
28
- console.log(` ${chalk.gray('├─')} worker.js`);
29
- console.log(` ${chalk.gray('├─')} schema.sql`);
30
- console.log(` ${chalk.gray('└─')} wrangler.toml`);
31
-
32
- console.log(chalk.cyan('\nPróximos passos:'));
33
- console.log(' 1. Configure suas API tokens no Wrangler:');
34
- console.log(' wrangler secret put META_ACCESS_TOKEN');
35
- console.log(' 2. Faça o deploy:');
36
- console.log(' wrangler deploy');
37
- console.log(' 3. Configure o schema D1:');
38
- console.log(' wrangler d1 execute db --file=schema.sql');
39
-
40
- } catch (error) {
41
- spinner.fail('Erro ao gerar infraestrutura');
42
- console.error(error);
43
- }
44
- }
45
-
46
- async function generateWorker(dir) {
47
- const workerPath = join(dir, 'worker.js');
48
- await fs.writeFile(workerPath, generateWorkerCode());
49
- }
50
-
51
- async function generateSchema(dir) {
52
- const schemaPath = join(dir, 'schema.sql');
53
- await fs.writeFile(schemaPath, generateSchemaCode());
54
- }
55
-
56
- async function generateWranglerConfig(dir) {
57
- const configPath = join(dir, 'wrangler.toml');
58
- await fs.writeFile(configPath, generateWranglerCode());
59
- }
60
-
61
- function generateWorkerCode() {
62
- return `// CDP Edge Quantum Tier - Cloudflare Worker
63
- // Auto-generated by cdp-edge npx
64
-
65
- export default {
66
- async fetch(request, env) {
67
- const url = new URL(request.url);
68
- const path = url.pathname;
69
-
70
- // Endpoint de tracking
71
- if (path === '/api/tracking') {
72
- return handleTracking(request, env);
73
- }
74
-
75
- // Health check
76
- if (path === '/health') {
77
- return new Response(JSON.stringify({ status: 'ok' }), {
78
- headers: { 'Content-Type': 'application/json' }
79
- });
80
- }
81
-
82
- return new Response('Not Found', { status: 404 });
83
- }
84
- };
85
-
86
- async function handleTracking(request, env) {
87
- try {
88
- const body = await request.json();
89
- const { event, data } = body;
90
-
91
- // Persistir no D1
92
- await env.DB.prepare(
93
- 'INSERT INTO events (event_id, event_type, user_id, data, created_at) VALUES (?, ?, ?, ?, ?)'
94
- ).bind(data.event_id, event, data.user_id, JSON.stringify(data), Date.now()).run();
95
-
96
- // Enviar para APIs externas (background)
97
- if (event === 'Purchase' || event === 'Lead') {
98
- ctx.waitUntil(sendToPlatforms(event, data, env));
99
- }
100
-
101
- return new Response(JSON.stringify({ success: true }), {
102
- headers: { 'Content-Type': 'application/json' }
103
- });
104
- } catch (error) {
105
- return new Response(JSON.stringify({ error: error.message }), {
106
- status: 500,
107
- headers: { 'Content-Type': 'application/json' }
108
- });
109
- }
110
- }
111
-
112
- async function sendToPlatforms(event, data, env) {
113
- // Implementar envio para Meta, TikTok, etc.
114
- // Use Promise.allSettled para resiliência
115
- }
116
- `;
117
- }
118
-
119
- function generateSchemaCode() {
120
- return `-- CDP Edge Quantum Tier - D1 Schema
121
- -- Auto-generated by cdp-edge npx
122
-
123
- -- Tabela de sessões/identidade
124
- CREATE TABLE IF NOT EXISTS identities (
125
- id TEXT PRIMARY KEY,
126
- user_id TEXT NOT NULL,
127
- email TEXT,
128
- phone TEXT,
129
- created_at INTEGER NOT NULL,
130
- updated_at INTEGER NOT NULL,
131
- INDEX idx_user_id (user_id)
132
- );
133
-
134
- -- Tabela de leads
135
- CREATE TABLE IF NOT EXISTS leads (
136
- id TEXT PRIMARY KEY,
137
- identity_id TEXT NOT NULL,
138
- email TEXT,
139
- phone TEXT,
140
- name TEXT,
141
- source TEXT,
142
- created_at INTEGER NOT NULL,
143
- FOREIGN KEY (identity_id) REFERENCES identities(id)
144
- );
145
-
146
- -- Tabela de eventos
147
- CREATE TABLE IF NOT EXISTS events (
148
- id INTEGER PRIMARY KEY AUTOINCREMENT,
149
- event_id TEXT NOT NULL UNIQUE,
150
- event_type TEXT NOT NULL,
151
- user_id TEXT,
152
- data TEXT,
153
- created_at INTEGER NOT NULL,
154
- INDEX idx_event_id (event_id),
155
- INDEX idx_event_type (event_type),
156
- INDEX idx_user_id (user_id)
157
- );
158
- `;
159
- }
160
-
161
- function generateWranglerCode() {
162
- return `# CDP Edge Quantum Tier - Wrangler Config
163
- # Auto-generated by cdp-edge npx
164
-
165
- name = "cdp-edge-worker"
166
- main = "worker.js"
167
- compatibility_date = "2024-01-01"
168
-
169
- [[d1_databases]]
170
- binding = "DB"
171
- database_name = "cdp-edge-db"
172
- database_id = "your-database-id"
173
- `;
174
- }
1
+ /**
2
+ * Server Command - Infraestrutura Cloudflare Workers
3
+ */
4
+
5
+ import chalk from 'chalk';
6
+ import ora from 'ora';
7
+ import { promises as fs } from 'fs';
8
+ import { join } from 'path';
9
+
10
+ export async function runServer(dir) {
11
+ console.log(chalk.cyan.bold('\n CDP Edge - Server-Side Tracking\n'));
12
+
13
+ const spinner = ora('Gerando infraestrutura...').start();
14
+
15
+ try {
16
+ // Gerar worker.js
17
+ await generateWorker(dir);
18
+
19
+ // Gerar schema.sql
20
+ await generateSchema(dir);
21
+
22
+ // Gerar wrangler.toml
23
+ await generateWranglerConfig(dir);
24
+
25
+ spinner.succeed(chalk.green('Infraestrutura gerada!'));
26
+
27
+ console.log('\n' + chalk.yellow('Arquivos gerados:'));
28
+ console.log(` ${chalk.gray('├─')} worker.js`);
29
+ console.log(` ${chalk.gray('├─')} schema.sql`);
30
+ console.log(` ${chalk.gray('└─')} wrangler.toml`);
31
+
32
+ console.log(chalk.cyan('\nPróximos passos:'));
33
+ console.log(' 1. Configure suas API tokens no Wrangler:');
34
+ console.log(' wrangler secret put META_ACCESS_TOKEN');
35
+ console.log(' 2. Faça o deploy:');
36
+ console.log(' wrangler deploy');
37
+ console.log(' 3. Configure o schema D1:');
38
+ console.log(' wrangler d1 execute db --file=schema.sql');
39
+
40
+ } catch (error) {
41
+ spinner.fail('Erro ao gerar infraestrutura');
42
+ console.error(error);
43
+ }
44
+ }
45
+
46
+ async function generateWorker(dir) {
47
+ const workerPath = join(dir, 'worker.js');
48
+ await fs.writeFile(workerPath, generateWorkerCode());
49
+ }
50
+
51
+ async function generateSchema(dir) {
52
+ const schemaPath = join(dir, 'schema.sql');
53
+ await fs.writeFile(schemaPath, generateSchemaCode());
54
+ }
55
+
56
+ async function generateWranglerConfig(dir) {
57
+ const configPath = join(dir, 'wrangler.toml');
58
+ await fs.writeFile(configPath, generateWranglerCode());
59
+ }
60
+
61
+ function generateWorkerCode() {
62
+ return `// CDP Edge Quantum Tier - Cloudflare Worker
63
+ // Auto-generated by cdp-edge npx
64
+
65
+ export default {
66
+ async fetch(request, env) {
67
+ const url = new URL(request.url);
68
+ const path = url.pathname;
69
+
70
+ // Endpoint de tracking
71
+ if (path === '/api/tracking') {
72
+ return handleTracking(request, env);
73
+ }
74
+
75
+ // Health check
76
+ if (path === '/health') {
77
+ return new Response(JSON.stringify({ status: 'ok' }), {
78
+ headers: { 'Content-Type': 'application/json' }
79
+ });
80
+ }
81
+
82
+ return new Response('Not Found', { status: 404 });
83
+ }
84
+ };
85
+
86
+ async function handleTracking(request, env) {
87
+ try {
88
+ const body = await request.json();
89
+ const { event, data } = body;
90
+
91
+ // Persistir no D1
92
+ await env.DB.prepare(
93
+ 'INSERT INTO events (event_id, event_type, user_id, data, created_at) VALUES (?, ?, ?, ?, ?)'
94
+ ).bind(data.event_id, event, data.user_id, JSON.stringify(data), Date.now()).run();
95
+
96
+ // Enviar para APIs externas (background)
97
+ if (event === 'Purchase' || event === 'Lead') {
98
+ ctx.waitUntil(sendToPlatforms(event, data, env));
99
+ }
100
+
101
+ return new Response(JSON.stringify({ success: true }), {
102
+ headers: { 'Content-Type': 'application/json' }
103
+ });
104
+ } catch (error) {
105
+ return new Response(JSON.stringify({ error: error.message }), {
106
+ status: 500,
107
+ headers: { 'Content-Type': 'application/json' }
108
+ });
109
+ }
110
+ }
111
+
112
+ async function sendToPlatforms(event, data, env) {
113
+ // Implementar envio para Meta, TikTok, etc.
114
+ // Use Promise.allSettled para resiliência
115
+ }
116
+ `;
117
+ }
118
+
119
+ function generateSchemaCode() {
120
+ return `-- CDP Edge Quantum Tier - D1 Schema
121
+ -- Auto-generated by cdp-edge npx
122
+
123
+ -- Tabela de sessões/identidade
124
+ CREATE TABLE IF NOT EXISTS identities (
125
+ id TEXT PRIMARY KEY,
126
+ user_id TEXT NOT NULL,
127
+ email TEXT,
128
+ phone TEXT,
129
+ created_at INTEGER NOT NULL,
130
+ updated_at INTEGER NOT NULL,
131
+ INDEX idx_user_id (user_id)
132
+ );
133
+
134
+ -- Tabela de leads
135
+ CREATE TABLE IF NOT EXISTS leads (
136
+ id TEXT PRIMARY KEY,
137
+ identity_id TEXT NOT NULL,
138
+ email TEXT,
139
+ phone TEXT,
140
+ name TEXT,
141
+ source TEXT,
142
+ created_at INTEGER NOT NULL,
143
+ FOREIGN KEY (identity_id) REFERENCES identities(id)
144
+ );
145
+
146
+ -- Tabela de eventos
147
+ CREATE TABLE IF NOT EXISTS events (
148
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
149
+ event_id TEXT NOT NULL UNIQUE,
150
+ event_type TEXT NOT NULL,
151
+ user_id TEXT,
152
+ data TEXT,
153
+ created_at INTEGER NOT NULL,
154
+ INDEX idx_event_id (event_id),
155
+ INDEX idx_event_type (event_type),
156
+ INDEX idx_user_id (user_id)
157
+ );
158
+ `;
159
+ }
160
+
161
+ function generateWranglerCode() {
162
+ return `# CDP Edge Quantum Tier - Wrangler Config
163
+ # Auto-generated by cdp-edge npx
164
+
165
+ name = "cdp-edge-worker"
166
+ main = "worker.js"
167
+ compatibility_date = "2024-01-01"
168
+
169
+ [[d1_databases]]
170
+ binding = "DB"
171
+ database_name = "cdp-edge-db"
172
+ database_id = "your-database-id"
173
+ `;
174
+ }
@@ -8,8 +8,26 @@ import inquirer from 'inquirer';
8
8
  import chalk from 'chalk';
9
9
  import ora from 'ora';
10
10
 
11
+ function printBanner() {
12
+ console.log('');
13
+ console.log(chalk.white.bold(' CDP Edge Setup Wizard'));
14
+ console.log('');
15
+ console.log(chalk.cyan(' ██████╗██████╗ ██████╗ ███████╗██████╗ ██████╗ ███████╗'));
16
+ console.log(chalk.cyan('██╔════╝██╔══██╗██╔══██╗ ██╔════╝██╔══██╗██╔════╝ ██╔════╝'));
17
+ console.log(chalk.cyan('██║ ██║ ██║██████╔╝ █████╗ ██║ ██║██║ ███╗█████╗ '));
18
+ console.log(chalk.cyan('██║ ██║ ██║██╔═══╝ ██╔══╝ ██║ ██║██║ ██║██╔══╝ '));
19
+ console.log(chalk.cyan('╚██████╗██████╔╝██║ ███████╗██████╔╝╚██████╔╝███████╗'));
20
+ console.log(chalk.cyan(' ╚═════╝╚═════╝ ╚═╝ ╚══════╝╚═════╝ ╚═════╝╚══════╝'));
21
+ console.log('');
22
+ console.log(chalk.gray(' Customer Data Platform on the Edge · Quantum Tracking · Cloudflare Native'));
23
+ console.log(chalk.gray(' Setup Wizard v2.0.0'));
24
+ console.log('');
25
+ console.log(chalk.gray('═'.repeat(68)));
26
+ console.log('');
27
+ }
28
+
11
29
  export async function runSetupWizard(dir = '.') {
12
- console.log(chalk.cyan.bold('\n CDP Edge Quantum Tier - Setup Wizard\n'));
30
+ printBanner();
13
31
 
14
32
  // === MENSAGEM INICIAL ===
15
33
 
@@ -1,84 +1,84 @@
1
- /**
2
- * Validate Command - Auditoria de tracking existente
3
- */
4
-
5
- import inquirer from 'inquirer';
6
- import chalk from 'chalk';
7
- import ora from 'ora';
8
- import { promises as fs } from 'fs';
9
-
10
- export async function runValidate(filePath) {
11
- console.log(chalk.cyan.bold('\n CDP Edge - Tracking Validator\n'));
12
-
13
- const input = await inquirer.prompt([
14
- {
15
- type: 'input',
16
- name: 'code',
17
- message: 'Cole o código de tracking para validar:',
18
- validate: (value) => value.length > 0 || 'Por favor, forneça o código'
19
- }
20
- ]);
21
-
22
- const spinner = ora('Validando código...').start();
23
-
24
- try {
25
- const validation = await validateCode(input.code);
26
-
27
- spinner.succeed('Validação concluída');
28
-
29
- console.log('\n' + chalk.yellow('Relatório de Validação:'));
30
- displayValidationReport(validation);
31
-
32
- } catch (error) {
33
- spinner.fail('Erro na validação');
34
- console.error(error);
35
- }
36
- }
37
-
38
- async function validateCode(code) {
39
- // Em produção, usaria o Validator Agent para análise profunda
40
- const issues = [];
41
- const warnings = [];
42
-
43
- // Validações básicas
44
- if (!code.includes('event_id')) {
45
- issues.push('Falta event_id para deduplicação');
46
- }
47
- if (!code.includes('SHA256') && !code.includes('sha256')) {
48
- warnings.push('Hashing não detectado para PII');
49
- }
50
- if (code.includes('dataLayer') || code.includes('gtm')) {
51
- issues.push('Detectado GTM - considere Cloudflare Workers Quantum Tier');
52
- }
53
-
54
- return {
55
- status: issues.length === 0 ? 'PASS' : 'FAIL',
56
- score: Math.max(0, 100 - (issues.length * 25) - (warnings.length * 10)),
57
- issues,
58
- warnings
59
- };
60
- }
61
-
62
- function displayValidationReport(validation) {
63
- // Status
64
- const statusColor = validation.status === 'PASS' ? 'green' : 'red';
65
- console.log(` Status: ${chalk[statusColor].bold(validation.status)}`);
66
- console.log(` Score: ${chalk.cyan(validation.score)}/100`);
67
-
68
- // Issues
69
- if (validation.issues.length > 0) {
70
- console.log('\n' + chalk.red.bold('❌ Problemas Críticos:'));
71
- validation.issues.forEach(issue => console.log(` ${chalk.red('├─')} ${issue}`));
72
- }
73
-
74
- // Warnings
75
- if (validation.warnings.length > 0) {
76
- console.log('\n' + chalk.yellow.bold('⚠️ Avisos:'));
77
- validation.warnings.forEach(warning => console.log(` ${chalk.yellow('├─')} ${warning}`));
78
- }
79
-
80
- // Sucesso
81
- if (validation.issues.length === 0 && validation.warnings.length === 0) {
82
- console.log('\n' + chalk.green.bold('✅ Código validado com sucesso!'));
83
- }
84
- }
1
+ /**
2
+ * Validate Command - Auditoria de tracking existente
3
+ */
4
+
5
+ import inquirer from 'inquirer';
6
+ import chalk from 'chalk';
7
+ import ora from 'ora';
8
+ import { promises as fs } from 'fs';
9
+
10
+ export async function runValidate(filePath) {
11
+ console.log(chalk.cyan.bold('\n CDP Edge - Tracking Validator\n'));
12
+
13
+ const input = await inquirer.prompt([
14
+ {
15
+ type: 'input',
16
+ name: 'code',
17
+ message: 'Cole o código de tracking para validar:',
18
+ validate: (value) => value.length > 0 || 'Por favor, forneça o código'
19
+ }
20
+ ]);
21
+
22
+ const spinner = ora('Validando código...').start();
23
+
24
+ try {
25
+ const validation = await validateCode(input.code);
26
+
27
+ spinner.succeed('Validação concluída');
28
+
29
+ console.log('\n' + chalk.yellow('Relatório de Validação:'));
30
+ displayValidationReport(validation);
31
+
32
+ } catch (error) {
33
+ spinner.fail('Erro na validação');
34
+ console.error(error);
35
+ }
36
+ }
37
+
38
+ async function validateCode(code) {
39
+ // Em produção, usaria o Validator Agent para análise profunda
40
+ const issues = [];
41
+ const warnings = [];
42
+
43
+ // Validações básicas
44
+ if (!code.includes('event_id')) {
45
+ issues.push('Falta event_id para deduplicação');
46
+ }
47
+ if (!code.includes('SHA256') && !code.includes('sha256')) {
48
+ warnings.push('Hashing não detectado para PII');
49
+ }
50
+ if (code.includes('dataLayer') || code.includes('gtm')) {
51
+ issues.push('Detectado GTM - considere Cloudflare Workers Quantum Tier');
52
+ }
53
+
54
+ return {
55
+ status: issues.length === 0 ? 'PASS' : 'FAIL',
56
+ score: Math.max(0, 100 - (issues.length * 25) - (warnings.length * 10)),
57
+ issues,
58
+ warnings
59
+ };
60
+ }
61
+
62
+ function displayValidationReport(validation) {
63
+ // Status
64
+ const statusColor = validation.status === 'PASS' ? 'green' : 'red';
65
+ console.log(` Status: ${chalk[statusColor].bold(validation.status)}`);
66
+ console.log(` Score: ${chalk.cyan(validation.score)}/100`);
67
+
68
+ // Issues
69
+ if (validation.issues.length > 0) {
70
+ console.log('\n' + chalk.red.bold('❌ Problemas Críticos:'));
71
+ validation.issues.forEach(issue => console.log(` ${chalk.red('├─')} ${issue}`));
72
+ }
73
+
74
+ // Warnings
75
+ if (validation.warnings.length > 0) {
76
+ console.log('\n' + chalk.yellow.bold('⚠️ Avisos:'));
77
+ validation.warnings.forEach(warning => console.log(` ${chalk.yellow('├─')} ${warning}`));
78
+ }
79
+
80
+ // Sucesso
81
+ if (validation.issues.length === 0 && validation.warnings.length === 0) {
82
+ console.log('\n' + chalk.green.bold('✅ Código validado com sucesso!'));
83
+ }
84
+ }
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- /**
2
- * CDP Edge CLI - Main Entry
3
- * Sistema multi-agente para tracking digital Quantum Tier
4
- */
5
-
6
- export { runSetupWizard } from './commands/setup.js';
7
- export { runAnalyze } from './commands/analyze.js';
8
- export { runServer } from './commands/server.js';
9
- export { runValidate } from './commands/validate.js';
10
- export { runInfra } from './commands/infra.js';
11
-
12
- export const version = '1.0.0';
1
+ /**
2
+ * CDP Edge CLI - Main Entry
3
+ * Sistema multi-agente para tracking digital Quantum Tier
4
+ */
5
+
6
+ export { runSetupWizard } from './commands/setup.js';
7
+ export { runAnalyze } from './commands/analyze.js';
8
+ export { runServer } from './commands/server.js';
9
+ export { runValidate } from './commands/validate.js';
10
+ export { runInfra } from './commands/infra.js';
11
+
12
+ export const version = '1.0.0';