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/API.md CHANGED
@@ -17,7 +17,9 @@ Este documento é a referência técnica oficial para a API da biblioteca `react
17
17
  | `useOpenPreferencesModal` | Hook | Retorna uma função para abrir o modal de preferências de forma programática. |
18
18
  | `openPreferencesModal` | Função | Versão da função acima para ser usada fora do contexto React. |
19
19
  | `ConsentGate` | Componente | Renderiza componentes filhos apenas se uma categoria de cookie for consentida. |
20
- | `ConsentScriptLoader` | Componente | Carrega scripts de terceiros (como Google Analytics) com base no consentimento. |
20
+ | `ConsentScriptLoader` | Componente | Carrega scripts de terceiros (como Google Analytics) com base no consentimento. Suporta Consent Mode v2 automático. |
21
+ | `registerScript()` | Função | Registra um script na fila global para execução condicional ao consentimento. Retorna função de cleanup. |
22
+ | `RegisteredScript` | Tipo | Interface para scripts registrados programaticamente (id, category, execute, priority, onConsentUpdate). |
21
23
  | `buildConsentStorageKey` | Função | (v0.5.2) Gera nomes de cookies `namespace__vX` a partir de namespace/versão. |
22
24
  | `createGoogleAnalyticsIntegration` | Função | Factory para integração nativa com o Google Analytics. |
23
25
  | `createGoogleTagManagerIntegration` | Função | Factory para integração nativa com o Google Tag Manager. |
@@ -33,6 +35,9 @@ Este documento é a referência técnica oficial para a API da biblioteca `react
33
35
  | `categorizeDiscoveredCookies` | Função | (v0.4.1) Categoriza cookies descobertos usando padrões LGPD. |
34
36
  | `getCookiesInfoForCategory` | Função | Retorna informações detalhadas dos cookies de uma categoria específica. |
35
37
  | `resolveTexts` | Função | (v0.4.1) Resolve textos baseados em templates e contexto. |
38
+ | `createConsentAuditEntry` | Função | **(v0.7.0)** Cria entrada de auditoria de consentimento para logs. |
39
+ | `ANPD_CATEGORY_PRESETS` | Constante | **(v0.7.0)** Presets de categorias conforme diretrizes LGPD/ANPD. |
40
+ | `createAnpdCategories` | Função | **(v0.7.0)** Helper para gerar configurações tipadas com presets ANPD. |
36
41
  | `TEXT_TEMPLATES` | Constante | (v0.4.1) Templates pré-configurados (ecommerce, saas, governo). |
37
42
  | `AdvancedConsentTexts` | Tipo | (v0.4.1) Interface expandida com i18n e contextos. |
38
43
  | `DesignTokens` | Tipo | (v0.4.1) Sistema completo com 200+ pontos de customização. |
@@ -80,6 +85,9 @@ function App() {
80
85
  | `disableFloatingPreferencesButton` | `boolean` | Remove o botão flutuante padrão. |
81
86
  | `onConsentGiven` | `(state: ConsentState) => void` | Dispara na primeira vez que o usuário aceita/rejeita. Útil para inicializar analytics. |
82
87
  | `onPreferencesSaved` | `(prefs: ConsentPreferences) => void` | Executa toda vez que o usuário salva preferências no modal. |
88
+ | `onConsentInit` | `(state: ConsentState) => void` | **(v0.7.0)** Callback executado após hidratação inicial do consentimento. |
89
+ | `onConsentChange` | `(state: ConsentState, previous: ConsentState) => void` | **(v0.7.0)** Callback executado sempre que o estado de consentimento muda. |
90
+ | `onAuditLog` | `(entry: ConsentAuditEntry) => void` | **(v0.7.0)** Callback para registrar eventos de auditoria (init, update, reset). |
83
91
  | `cookie` | `Partial<ConsentCookieOptions>` | Override fino das opções de cookie (nome, expiração, sameSite, secure, path, domain). Se `name` não for informado, o valor deriva de `storage`. |
84
92
  | `storage` | `ConsentStorageConfig` | Define namespace, versão e domínio compartilhado. Gera automaticamente o nome da chave (`namespace__vX`). Alterar `version` força re-consentimento. |
85
93
  | `onConsentVersionChange` | `(context: ConsentVersionChangeContext) => void` | Notificado após mudança da chave de storage. O reset já é automático; use o hook para limpar caches externos ou registrar eventos. |
@@ -169,12 +177,35 @@ function MyComponent() {
169
177
 
170
178
  Gerencia o carregamento de scripts de terceiros (ex: Google Analytics) com base no consentimento do usuário. Veja o guia `INTEGRACOES.md` para mais detalhes.
171
179
 
180
+ **Novidades v0.7.1:**
181
+ - ✨ **Google Consent Mode v2 automático**: GA4 e GTM agora enviam `consent('default', 'denied')` no bootstrap e `consent('update', 'granted')` após consentimento
182
+ - 🎯 **Sistema de fila com prioridade**: Scripts são executados ordenadamente (necessary → categoria → prioridade → timestamp)
183
+ - 🔄 **Callbacks de atualização**: `onConsentUpdate` dispara quando preferências mudam
184
+
172
185
  ```tsx
173
- import { ConsentScriptLoader, createGoogleAnalyticsIntegration } from 'react-lgpd-consent'
186
+ import { ConsentScriptLoader, createGoogleAnalyticsIntegration, registerScript } from 'react-lgpd-consent'
174
187
 
188
+ // Uso padrão (Consent Mode v2 automático)
175
189
  const integrations = [createGoogleAnalyticsIntegration({ measurementId: 'G-XXXXXXXXXX' })]
190
+ <ConsentScriptLoader integrations={integrations} />
191
+
192
+ // Uso avançado: registro programático com prioridade
193
+ const cleanup = registerScript({
194
+ id: 'custom-analytics',
195
+ category: 'analytics',
196
+ priority: 10, // Maior = executa primeiro
197
+ execute: async () => {
198
+ console.log('Script carregado!')
199
+ },
200
+ onConsentUpdate: ({ consented, preferences }) => {
201
+ if (preferences.analytics) {
202
+ console.log('Analytics habilitado via update!')
203
+ }
204
+ }
205
+ })
176
206
 
177
- ;<ConsentScriptLoader integrations={integrations} />
207
+ // ℹ️ Estados da fila: pending → running → executed.
208
+ // Scripts só reexecutam se allowReload=true; sempre use o cleanup ao desmontar.
178
209
  ```
179
210
 
180
211
  ---
@@ -574,3 +605,141 @@ Conjunto completo (site com analytics/marketing):
574
605
  <App />
575
606
  </ConsentProvider>
576
607
  ```
608
+
609
+ ---
610
+
611
+ ## 🆕 Novidades v0.7.0
612
+
613
+ ### Callbacks de Lifecycle (#68)
614
+
615
+ Monitore eventos de consentimento para integração com sistemas de auditoria:
616
+
617
+ ```tsx
618
+ import { ConsentProvider, createConsentAuditEntry } from 'react-lgpd-consent'
619
+
620
+ function App() {
621
+ return (
622
+ <ConsentProvider
623
+ categories={{ enabledCategories: ['analytics', 'marketing'] }}
624
+ onConsentInit={(state) => {
625
+ console.log('Consentimento inicializado:', state)
626
+ // Útil para analytics iniciais
627
+ }}
628
+ onConsentChange={(current, previous) => {
629
+ console.log('Consentimento alterado:', { current, previous })
630
+ // Dispara em toda mudança de preferências
631
+ }}
632
+ onAuditLog={(entry) => {
633
+ // Registrar no backend para compliance
634
+ fetch('/api/consent-audit', {
635
+ method: 'POST',
636
+ body: JSON.stringify(entry),
637
+ })
638
+ }}
639
+ >
640
+ <YourApp />
641
+ </ConsentProvider>
642
+ )
643
+ }
644
+ ```
645
+
646
+ **Tipos disponíveis:**
647
+
648
+ ```typescript
649
+ interface ConsentAuditEntry {
650
+ timestamp: string // ISO 8601
651
+ action: 'init' | 'update' | 'reset'
652
+ state: ConsentState
653
+ metadata?: {
654
+ storageKey?: string
655
+ consentVersion?: string
656
+ userAgent?: string
657
+ }
658
+ }
659
+ ```
660
+
661
+ ### Presets de Categorias ANPD (#70)
662
+
663
+ Use presets conformes com diretrizes da ANPD:
664
+
665
+ ```tsx
666
+ import { ConsentProvider, createAnpdCategories, ANPD_CATEGORY_PRESETS } from 'react-lgpd-consent'
667
+
668
+ // Preset BÁSICO (necessary + analytics)
669
+ const basicConfig = createAnpdCategories({ include: ['analytics'] })
670
+
671
+ // Preset COMPLETO (todas as categorias)
672
+ const fullConfig = createAnpdCategories({
673
+ include: ['analytics', 'marketing', 'functional', 'social', 'personalization']
674
+ })
675
+
676
+ // Preset MÍNIMO (apenas necessary)
677
+ const minimalConfig = createAnpdCategories({ include: [] })
678
+
679
+ // Com customizações
680
+ const customConfig = createAnpdCategories({
681
+ include: ['analytics', 'marketing'],
682
+ names: { analytics: 'Análises' },
683
+ descriptions: { marketing: 'Anúncios personalizados baseados no seu perfil.' }
684
+ })
685
+
686
+ function App() {
687
+ return (
688
+ <ConsentProvider categories={fullConfig}>
689
+ <YourApp />
690
+ </ConsentProvider>
691
+ )
692
+ }
693
+ ```
694
+
695
+ **Preset disponível:**
696
+
697
+ ```typescript
698
+ export const ANPD_CATEGORY_PRESETS: Record<Category, CategoryDefinition> = {
699
+ necessary: { /* ... */ },
700
+ analytics: { /* ... */ },
701
+ functional: { /* ... */ },
702
+ marketing: { /* ... */ },
703
+ social: { /* ... */ },
704
+ personalization: { /* ... */ }
705
+ }
706
+ ```
707
+
708
+ ### Mensagens de Erro Melhoradas (#71)
709
+
710
+ Hooks agora lançam erros claros em pt-BR quando usados fora do `<ConsentProvider>`:
711
+
712
+ ```tsx
713
+ import { useConsent } from 'react-lgpd-consent'
714
+
715
+ function MyComponent() {
716
+ const consent = useConsent() // ❌ Erro claro!
717
+ // Error: [react-lgpd-consent] useConsent deve ser usado dentro de <ConsentProvider>.
718
+ // Envolva seu componente com o provider ou use o wrapper @react-lgpd-consent/mui.
719
+ }
720
+ ```
721
+
722
+ ### Auditoria e Compliance (#60)
723
+
724
+ Crie entradas de auditoria manualmente:
725
+
726
+ ```typescript
727
+ import { createConsentAuditEntry } from 'react-lgpd-consent'
728
+
729
+ const auditEntry = createConsentAuditEntry(
730
+ { consented: true, preferences: { analytics: true } },
731
+ {
732
+ action: 'update',
733
+ storageKey: 'lgpd-consent__v1',
734
+ consentVersion: '1'
735
+ }
736
+ )
737
+
738
+ // Enviar para backend
739
+ await fetch('/api/audit', {
740
+ method: 'POST',
741
+ body: JSON.stringify(auditEntry)
742
+ })
743
+ ```
744
+
745
+ Consulte [TROUBLESHOOTING.md - Auditoria e log de consentimento](../../TROUBLESHOOTING.md#auditoria-e-log-de-consentimento) para exemplos completos de integração com backend.