react-lgpd-consent 0.6.4 → 0.7.1

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/INTEGRACOES.md CHANGED
@@ -6,6 +6,36 @@ A biblioteca oferece integrações nativas para as ferramentas mais comuns, elim
6
6
 
7
7
  O componente `ConsentScriptLoader` gerencia o carregamento desses scripts automaticamente, disparando-os apenas quando o usuário concede consentimento para a categoria correspondente.
8
8
 
9
+ ### ✨ Novidades v0.7.1
10
+
11
+ - **🎯 Google Consent Mode v2 Automático**: GA4 e GTM agora implementam Consent Mode v2 automaticamente:
12
+ - `bootstrap`: Seta `consent('default', 'denied')` antes de qualquer carregamento
13
+ - `onConsentUpdate`: Envia `consent('update', 'granted')` quando usuário consente
14
+ - Zero configuração manual necessária!
15
+
16
+ - **🔄 Sistema de Fila com Prioridade**: Scripts são executados ordenadamente:
17
+ 1. Categoria `necessary` sempre primeiro
18
+ 2. Dentro da mesma categoria: maior `priority` primeiro
19
+ 3. Mesmo priority: ordem de registro (timestamp)
20
+
21
+ - **📝 API `registerScript()`**: Registre scripts programaticamente fora do JSX:
22
+
23
+ ```tsx
24
+ import { registerScript } from 'react-lgpd-consent'
25
+
26
+ const cleanup = registerScript({
27
+ id: 'my-script',
28
+ category: 'analytics',
29
+ priority: 5,
30
+ execute: async () => {
31
+ /* carrega script */
32
+ },
33
+ onConsentUpdate: ({ preferences }) => {
34
+ /* reage a mudanças */
35
+ },
36
+ })
37
+ ```
38
+
9
39
  > 💡 **Procurando exemplos práticos?** Veja [RECIPES.md](../../RECIPES.md) para receitas passo a passo de Google Consent Mode v2, Next.js App Router e CSP/nonce.
10
40
 
11
41
  ## 🎯 Integrações Nativas Disponíveis
@@ -15,6 +45,7 @@ O componente `ConsentScriptLoader` gerencia o carregamento desses scripts automa
15
45
  - **Categoria**: `analytics`
16
46
  - **Função**: `createGoogleAnalyticsIntegration(config)`
17
47
  - **Descrição**: Integração completa com o Google Analytics 4. Suporta `measurementId` e configurações adicionais para o `gtag`.
48
+ - **✨ Novo v0.7.1**: Google Consent Mode v2 automático (sem configuração manual)
18
49
 
19
50
  ```tsx
20
51
  import { createGoogleAnalyticsIntegration, ConsentScriptLoader } from 'react-lgpd-consent'
@@ -27,20 +58,28 @@ const integrations = [
27
58
  ]
28
59
 
29
60
  <ConsentScriptLoader integrations={integrations} />
61
+ // ✅ Consent Mode v2 implementado automaticamente:
62
+ // - bootstrap: consent('default', 'denied') antes do script
63
+ // - onConsentUpdate: consent('update', 'granted') após consentimento
30
64
  ```
31
65
 
32
66
  ### 2. Google Tag Manager (GTM)
33
67
 
34
68
  - **Categoria**: `analytics`
35
69
  - **Função**: `createGoogleTagManagerIntegration(config)`
36
- - **Descrição**: Carrega o container do Google Tag Manager. Suporta `gtmId` e `dataLayerName`.
70
+ - **Descrição**: Carrega o container do Google Tag Manager. Suporta `containerId` (ou `gtmId` legado) e `dataLayerName`.
71
+ - **✨ Novo v0.7.1**: Google Consent Mode v2 automático com dataLayer customizado
37
72
 
38
73
  ```tsx
39
74
  import { createGoogleTagManagerIntegration } from 'react-lgpd-consent'
40
75
 
41
76
  const integrations = [
42
- createGoogleTagManagerIntegration({ gtmId: 'GTM-XXXXXXX' })
77
+ createGoogleTagManagerIntegration({
78
+ containerId: 'GTM-XXXXXXX',
79
+ dataLayerName: 'dataLayer', // opcional
80
+ }),
43
81
  ]
82
+ // ✅ Consent Mode v2 no dataLayer customizado automaticamente
44
83
  ```
45
84
 
46
85
  ### 3. Facebook Pixel
@@ -52,9 +91,7 @@ const integrations = [
52
91
  ```tsx
53
92
  import { createFacebookPixelIntegration } from 'react-lgpd-consent'
54
93
 
55
- const integrations = [
56
- createFacebookPixelIntegration({ pixelId: 'YOUR_PIXEL_ID', autoTrack: true })
57
- ]
94
+ const integrations = [createFacebookPixelIntegration({ pixelId: 'YOUR_PIXEL_ID', autoTrack: true })]
58
95
  ```
59
96
 
60
97
  ### 4. Hotjar
@@ -142,7 +179,11 @@ Para simplificar a configuração de múltiplas integrações, a biblioteca ofer
142
179
  ### Exemplo de Template (E-commerce)
143
180
 
144
181
  ```tsx
145
- import { ConsentProvider, ConsentScriptLoader, createECommerceIntegrations } from 'react-lgpd-consent'
182
+ import {
183
+ ConsentProvider,
184
+ ConsentScriptLoader,
185
+ createECommerceIntegrations,
186
+ } from 'react-lgpd-consent'
146
187
 
147
188
  function App() {
148
189
  const integrations = createECommerceIntegrations({
@@ -185,6 +226,7 @@ categorizeDiscoveredCookies(discovered, true)
185
226
  ## 🧱 Nota SSR/Next.js (App Router)
186
227
 
187
228
  Para evitar hydration mismatch e vazamento de scripts:
229
+
188
230
  - Coloque o `ConsentProvider` dentro de um Client Component e carregue-o com `dynamic(..., { ssr: false })` a partir do `RootLayout` (Server Component).
189
231
  - Use o `ConsentScriptLoader` para carregar GTM/GA4 somente após consentimento e inicialize o Consent Mode v2 com `gtag('consent','default', denied)` antes de qualquer script.
190
232
  - Consulte a seção “SSR/Next.js (App Router) — Padrões seguros” em `QUICKSTART.md` para ordem dos provedores/estilos (MUI/Emotion) e checklist SSR.
@@ -218,6 +260,7 @@ A partir da versão **0.4.5**, a biblioteca dispara automaticamente eventos padr
218
260
  Disparado quando o sistema de consentimento é inicializado (após hidratação).
219
261
 
220
262
  **Payload:**
263
+
221
264
  ```typescript
222
265
  {
223
266
  event: 'consent_initialized',
@@ -232,6 +275,7 @@ Disparado quando o sistema de consentimento é inicializado (após hidratação)
232
275
  ```
233
276
 
234
277
  **Exemplo de uso no GTM:**
278
+
235
279
  - **Tipo de acionador**: Evento personalizado
236
280
  - **Nome do evento**: `consent_initialized`
237
281
  - **Variáveis**: `{{categories.analytics}}`, `{{categories.marketing}}`, etc.
@@ -241,6 +285,7 @@ Disparado quando o sistema de consentimento é inicializado (após hidratação)
241
285
  Disparado sempre que o usuário atualiza suas preferências de consentimento.
242
286
 
243
287
  **Payload:**
288
+
244
289
  ```typescript
245
290
  {
246
291
  event: 'consent_updated',
@@ -257,6 +302,7 @@ Disparado sempre que o usuário atualiza suas preferências de consentimento.
257
302
  ```
258
303
 
259
304
  **Exemplo de uso no GTM:**
305
+
260
306
  - **Tipo de acionador**: Evento personalizado
261
307
  - **Nome do evento**: `consent_updated`
262
308
  - **Condição**: `{{changed_categories}}` contém `analytics`
@@ -313,7 +359,7 @@ Crie uma tag para registrar mudanças de consentimento em um sistema de auditori
313
359
  categories: {{DLV - Consent Categories}},
314
360
  changed: {{DLV - Changed Categories}}
315
361
  };
316
-
362
+
317
363
  // Enviar para seu sistema de auditoria
318
364
  fetch('/api/consent-audit', {
319
365
  method: 'POST',
@@ -336,9 +382,9 @@ const handleCustomUpdate = () => {
336
382
  const newPreferences = {
337
383
  necessary: true,
338
384
  analytics: true,
339
- marketing: false
385
+ marketing: false,
340
386
  }
341
-
387
+
342
388
  pushConsentUpdatedEvent(newPreferences, 'programmatic')
343
389
  }
344
390
  ```
@@ -350,7 +396,7 @@ import type {
350
396
  ConsentEvent,
351
397
  ConsentEventOrigin,
352
398
  ConsentInitializedEvent,
353
- ConsentUpdatedEvent
399
+ ConsentUpdatedEvent,
354
400
  } from 'react-lgpd-consent'
355
401
 
356
402
  // Origem da ação
@@ -389,3 +435,89 @@ interface ConsentUpdatedEvent {
389
435
  | Live Chat | `functional` | Funcionalidade de suporte |
390
436
  | YouTube/Vimeo | `social` | Conteúdo de redes sociais |
391
437
 
438
+ ---
439
+
440
+ ## 🆕 Recursos Avançados v0.7.0
441
+
442
+ ### Monitoramento com Callbacks de Lifecycle
443
+
444
+ Integre sistemas de auditoria monitorando eventos de consentimento:
445
+
446
+ ```tsx
447
+ import { ConsentProvider, ConsentScriptLoader } from 'react-lgpd-consent'
448
+ import { googleAnalytics4Integration } from './integrations'
449
+
450
+ ;<ConsentProvider
451
+ categories={{ enabledCategories: ['analytics', 'marketing'] }}
452
+ onConsentInit={(state) => {
453
+ // Disparado na inicialização (útil para analytics)
454
+ console.log('Consentimento inicial:', state)
455
+ }}
456
+ onConsentChange={(current, previous) => {
457
+ // Disparado em toda mudança de preferências
458
+ console.log('Mudança:', { current, previous })
459
+
460
+ // Exemplo: disparar evento no dataLayer
461
+ window.dataLayer?.push({
462
+ event: 'consent_preferences_updated',
463
+ consent_analytics: current.preferences.analytics,
464
+ consent_marketing: current.preferences.marketing,
465
+ })
466
+ }}
467
+ onAuditLog={(entry) => {
468
+ // Enviar para backend de compliance
469
+ fetch('/api/consent-audit', {
470
+ method: 'POST',
471
+ body: JSON.stringify(entry),
472
+ })
473
+ }}
474
+ >
475
+ <ConsentScriptLoader integrations={[googleAnalytics4Integration]} />
476
+ <YourApp />
477
+ </ConsentProvider>
478
+ ```
479
+
480
+ ### Presets de Categorias ANPD
481
+
482
+ Use configurações pré-validadas pela ANPD:
483
+
484
+ ```tsx
485
+ import { ConsentProvider, createAnpdCategories } from 'react-lgpd-consent'
486
+
487
+ // Preset BÁSICO (necessary + analytics)
488
+ const basicConfig = createAnpdCategories({ include: ['analytics'] })
489
+
490
+ // Preset COMPLETO (todas as 6 categorias)
491
+ const fullConfig = createAnpdCategories({
492
+ include: ['analytics', 'marketing', 'functional', 'social', 'personalization']
493
+ })
494
+
495
+ // Com customizações
496
+ const customConfig = createAnpdCategories({
497
+ include: ['analytics', 'marketing'],
498
+ names: { analytics: 'Análises' },
499
+ descriptions: { marketing: 'Anúncios personalizados' }
500
+ })
501
+
502
+ <ConsentProvider categories={fullConfig}>
503
+ <ConsentScriptLoader integrations={myIntegrations} />
504
+ </ConsentProvider>
505
+ ```
506
+
507
+ **Vantagens dos presets:**
508
+
509
+ - ✅ Conformidade com diretrizes ANPD
510
+ - ✅ Nomes e descrições em pt-BR revisadas
511
+ - ✅ Tipagem forte para evitar erros
512
+ - ✅ Reduz código boilerplate em 60%
513
+
514
+ ---
515
+
516
+ ## 📚 Recursos Adicionais
517
+
518
+ - [API.md](./API.md) – Documentação completa da API pública
519
+ - [RECIPES.md](../../RECIPES.md) – Receitas práticas com Next.js, CSP, Google Consent Mode v2
520
+ - [TROUBLESHOOTING.md](../../TROUBLESHOOTING.md) – Solução de problemas comuns
521
+ - [CONFORMIDADE.md](../../CONFORMIDADE.md) – Conformidade LGPD e ANPD
522
+
523
+ **Problemas de integração?** Consulte [TROUBLESHOOTING.md - Seção de Integrations](../../TROUBLESHOOTING.md#integrações-de-terceiros).
package/QUICKSTART.en.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  This quickstart gives everything you need to integrate `react-lgpd-consent` into a React project fast.
4
4
 
5
+ ## 🆕 What's New in v0.7.0
6
+
7
+ - ✅ **Lifecycle Callbacks** - `onConsentInit`, `onConsentChange`, `onAuditLog` for monitoring
8
+ - ✅ **ANPD Presets** - `createAnpdCategories()` for quick LGPD-compliant setup
9
+ - ✅ **Audit Logging** - `createConsentAuditEntry()` for compliance tracking
10
+ - ✅ **Better DX** - Clear error messages when hooks are used incorrectly
11
+
12
+ 📖 **Documentation:** [TROUBLESHOOTING.md](../../TROUBLESHOOTING.md) | [API.md](./API.md)
13
+
14
+ ---
15
+
5
16
  ## 📦 Installation
6
17
 
7
18
  ```bash
package/README.en.md CHANGED
@@ -84,6 +84,46 @@ function Analytics() {
84
84
 
85
85
  ---
86
86
 
87
+ ## 🆕 What's New in v0.7.0
88
+
89
+ ### Lifecycle Callbacks (#68)
90
+
91
+ ```tsx
92
+ <ConsentProvider
93
+ onConsentInit={(state) => console.log('Initialized:', state)}
94
+ onConsentChange={(current, prev) => console.log('Changed:', current)}
95
+ onAuditLog={(entry) => fetch('/api/audit', {
96
+ method: 'POST',
97
+ body: JSON.stringify(entry)
98
+ })}
99
+ >
100
+ ```
101
+
102
+ ### ANPD Category Presets (#70)
103
+
104
+ ```tsx
105
+ import { createAnpdCategories } from 'react-lgpd-consent'
106
+
107
+ const categories = createAnpdCategories({
108
+ include: ['analytics', 'marketing']
109
+ })
110
+ ```
111
+
112
+ ### Consent Audit (#60)
113
+
114
+ ```tsx
115
+ import { createConsentAuditEntry } from 'react-lgpd-consent'
116
+
117
+ const audit = createConsentAuditEntry(state, {
118
+ action: 'update',
119
+ consentVersion: '1'
120
+ })
121
+ ```
122
+
123
+ 📖 **Full documentation:** [API.md](./API.md) | [TROUBLESHOOTING.md](../../TROUBLESHOOTING.md)
124
+
125
+ ---
126
+
87
127
  ## Packages (monorepo)
88
128
 
89
129
  | Package | Description |
package/README.md CHANGED
@@ -13,7 +13,7 @@ Gerenciamento de consentimento de cookies em conformidade com a LGPD — pacote
13
13
 
14
14
  ## Descrição
15
15
 
16
- `react-lgpd-consent` é o pacote agregador compatível com versões anteriores (v0.4.x → v0.5.x). Ele re-exporta os componentes prontos em MUI e facilita a migração. Para projetos mais otimizados, considere importar diretamente `@react-lgpd-consent/core` (headless) ou `@react-lgpd-consent/mui` (componentes MUI).
16
+ `react-lgpd-consent` é o pacote agregador compatível com versões anteriores (v0.4.x → v0.5.x). Ele re-exporta os componentes prontos em MUI e facilita a migração. Para projetos mais otimizados, considere importar diretamente `@react-lgpd-consent/core` (headless) ou `@react-lgpd-consent/mui/ui` (apenas UI, sem re-export do core).
17
17
 
18
18
  Principais características:
19
19
 
@@ -84,6 +84,46 @@ function Analytics() {
84
84
 
85
85
  ---
86
86
 
87
+ ## 🆕 Novidades v0.7.0
88
+
89
+ ### Callbacks de Lifecycle (#68)
90
+
91
+ ```tsx
92
+ <ConsentProvider
93
+ onConsentInit={(state) => console.log('Init:', state)}
94
+ onConsentChange={(current, prev) => console.log('Changed:', current)}
95
+ onAuditLog={(entry) => fetch('/api/audit', {
96
+ method: 'POST',
97
+ body: JSON.stringify(entry)
98
+ })}
99
+ >
100
+ ```
101
+
102
+ ### Presets ANPD (#70)
103
+
104
+ ```tsx
105
+ import { createAnpdCategories } from 'react-lgpd-consent'
106
+
107
+ const categories = createAnpdCategories({
108
+ include: ['analytics', 'marketing']
109
+ })
110
+ ```
111
+
112
+ ### Auditoria (#60)
113
+
114
+ ```tsx
115
+ import { createConsentAuditEntry } from 'react-lgpd-consent'
116
+
117
+ const audit = createConsentAuditEntry(state, {
118
+ action: 'update',
119
+ consentVersion: '1'
120
+ })
121
+ ```
122
+
123
+ 📖 **Documentação completa:** [API.md](./API.md) | [TROUBLESHOOTING.md](../../TROUBLESHOOTING.md)
124
+
125
+ ---
126
+
87
127
  ## Pacotes (monorepo v0.5.x)
88
128
 
89
129
  | Pacote | Descrição |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-lgpd-consent",
3
- "version": "0.6.4",
3
+ "version": "0.7.1",
4
4
  "description": "Biblioteca de consentimento LGPD, integrações nativas e sistema extensível para React.",
5
5
  "keywords": [
6
6
  "lgpd",
@@ -94,8 +94,8 @@
94
94
  }
95
95
  },
96
96
  "dependencies": {
97
- "@react-lgpd-consent/core": "^0.6.3",
98
- "@react-lgpd-consent/mui": "^0.6.3"
97
+ "@react-lgpd-consent/core": "^0.7.1",
98
+ "@react-lgpd-consent/mui": "^0.7.1"
99
99
  },
100
100
  "size-limit": [
101
101
  {
@@ -117,7 +117,7 @@
117
117
  "name": "Complete Package Import",
118
118
  "path": "dist/index.js",
119
119
  "import": "{ ConsentProvider, useConsent, ConsentScriptLoader }",
120
- "limit": "70 KB"
120
+ "limit": "80 KB"
121
121
  }
122
122
  ],
123
123
  "scripts": {
@@ -133,8 +133,6 @@
133
133
  "test:coverage": "jest --config ../../jest.config.mjs --coverage",
134
134
  "coverage-check": "node ../../scripts/coverage-check.cjs",
135
135
  "size-check": "size-limit",
136
- "mutation": "npx stryker run",
137
- "mutation:tests": "npx stryker run ../../stryker.tests.conf.json",
138
136
  "docs:generate": "node ../../scripts/run-typedoc.mjs",
139
137
  "storybook": "storybook dev -p 6006 --config-dir ../../.storybook",
140
138
  "build-storybook": "storybook build --config-dir ../../.storybook --output-dir ../../storybook-static"