react-lgpd-consent 0.7.1 → 0.7.2

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
@@ -30,6 +30,7 @@ Este documento é a referência técnica oficial para a API da biblioteca `react
30
30
  | `createClarityIntegration` | Função | (v0.4.1) Integração nativa com Microsoft Clarity. |
31
31
  | `createIntercomIntegration` | Função | (v0.4.1) Integração nativa com Intercom (chat). |
32
32
  | `createZendeskChatIntegration` | Função | (v0.4.1) Integração nativa com Zendesk Chat. |
33
+ | `createSuggestedIntegration` | Função | (v0.7.2) Cria integração customizada com categoria sugerida automaticamente. |
33
34
  | `suggestCategoryForScript` | Função | (v0.4.1) Sugere categoria(s) LGPD para um script conhecido. |
34
35
  | `discoverRuntimeCookies` | Função | (v0.4.1) Descobre cookies em tempo real no navegador. |
35
36
  | `categorizeDiscoveredCookies` | Função | (v0.4.1) Categoriza cookies descobertos usando padrões LGPD. |
@@ -45,10 +46,63 @@ Este documento é a referência técnica oficial para a API da biblioteca `react
45
46
  | `createSaaSIntegrations` | Função | (v0.4.1) Cria integrações comuns para SaaS. |
46
47
  | `createCorporateIntegrations` | Função | (v0.4.1) Cria integrações comuns para ambientes corporativos. |
47
48
  | `INTEGRATION_TEMPLATES` | Constante | (v0.4.1) Presets com IDs essenciais/opcionais e categorias por tipo de negócio. |
49
+ | `SuggestedIntegrationConfig` | Tipo | (v0.7.2) Configuração para integração customizada com categoria sugerida. |
48
50
  | `setDebugLogging` | Função | Habilita/desabilita o logging de debug da biblioteca. |
49
51
 
50
52
  ---
51
53
 
54
+ ## ESM/CJS e Testes (Jest/Vitest)
55
+
56
+ O pacote publica **dual build** (ESM + CJS) via `exports`:
57
+
58
+ ```json
59
+ {
60
+ ".": { "import": "./dist/index.js", "require": "./dist/index.cjs" },
61
+ "./core": { "import": "./dist/core.js", "require": "./dist/core.cjs" },
62
+ "./mui": { "import": "./dist/mui.js", "require": "./dist/mui.cjs" },
63
+ "./integrations": { "import": "./dist/integrations.js", "require": "./dist/integrations.cjs" }
64
+ }
65
+ ```
66
+
67
+ ### Jest (CJS) com babel-jest
68
+
69
+ ```js
70
+ // jest.config.cjs
71
+ module.exports = {
72
+ testEnvironment: 'jsdom',
73
+ transform: {
74
+ '^.+\\.(t|j)sx?$': ['babel-jest', { presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'] }],
75
+ },
76
+ transformIgnorePatterns: ['/node_modules/(?!react-lgpd-consent|@react-lgpd-consent)/'],
77
+ }
78
+ ```
79
+
80
+ ### Vitest (Vite)
81
+
82
+ ```ts
83
+ // vitest.config.ts
84
+ import { defineConfig } from 'vitest/config'
85
+
86
+ export default defineConfig({
87
+ test: {
88
+ environment: 'jsdom',
89
+ deps: {
90
+ inline: ['react-lgpd-consent', '@react-lgpd-consent/core', '@react-lgpd-consent/mui'],
91
+ },
92
+ },
93
+ })
94
+ ```
95
+
96
+ ### Importações recomendadas
97
+
98
+ ```ts
99
+ import { ConsentProvider } from 'react-lgpd-consent'
100
+ import { ConsentProvider as ConsentProviderHeadless } from 'react-lgpd-consent/core'
101
+ import { createGoogleAnalyticsIntegration } from 'react-lgpd-consent/integrations'
102
+ ```
103
+
104
+ ---
105
+
52
106
  ## Componentes
53
107
 
54
108
  ### `<ConsentProvider />`
@@ -76,7 +130,9 @@ function App() {
76
130
  | Prop | Tipo | Descrição |
77
131
  | --- | --- | --- |
78
132
  | `categories` | `ProjectCategoriesConfig` | **Obrigatório.** Fonte única de verdade sobre as categorias habilitadas; usada por UI, hooks e integrações. |
79
- | `texts` | `Partial<ConsentTexts>` | Customiza todos os textos exibidos (banner, modal, botão). |
133
+ | `texts` | `Partial<AdvancedConsentTexts>` | Customiza todos os textos exibidos (banner, modal, botão). |
134
+ | `language` | `'pt' \| 'en' \| 'es' \| 'fr' \| 'de' \| 'it'` | Resolve textos via i18n no Provider. |
135
+ | `textVariant` | `'formal' \| 'casual' \| 'concise' \| 'detailed'` | Aplica variação de tom sobre os textos base. |
80
136
  | `designTokens` | `DesignTokens` | Ajuste visual granular (cores, spacing, tipografia, overlays). |
81
137
  | `blocking` | `boolean` | Ativa overlay bloqueante até o usuário decidir. Padrão: `false`. |
82
138
  | `blockingStrategy` | `'auto' \| 'provider' \| 'component'` | Controla quem desenha o overlay quando `blocking` está ativo. |
@@ -586,7 +642,7 @@ Para customizações avançadas e tipagem, você pode importar os seguintes tipo
586
642
  - `CustomPreferencesModalProps`: Props passadas para um modal de preferências customizado.
587
643
  - `ConsentState`: Objeto que representa o estado completo do consentimento do usuário.
588
644
  - `ConsentPreferences`: Objeto com as preferências de consentimento para cada categoria.
589
- - `ConsentTexts`: Objeto com todos os textos customizáveis da UI.
645
+ - `ConsentTexts`: Tipo base com textos essenciais da UI (pt-BR).
590
646
  - `Category`: Objeto que representa a definição de uma categoria de cookie.
591
647
  ### Exemplos de categorias (mínimo e completo)
592
648
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [#134](https://github.com/lucianoedipo/react-lgpd-consent/pull/134) [`44b885b`](https://github.com/lucianoedipo/react-lgpd-consent/commit/44b885b7c81f1cb5822e2dcfde2975e69e8d4893) Thanks [@github-actions](https://github.com/apps/github-actions)! - ### Correções
8
+ - 1d15920 fix: corrigir formatação da verificação de múltiplas versões do React
9
+
10
+ ### Funcionalidades
11
+ - d641639 feat: adicionar gerenciamento de eventos para categorias obrigatórias no CategoriesProvider
12
+ - b04c00b feat: add tests for CookieBanner, FloatingPreferencesButton, and PreferencesModal components
13
+ - b04c00b Introduce interactive changeset script for easier versioning in monorepos.
14
+
15
+ ### Refactors e compatibilidade
16
+ - ef2968a refactor: replace direct document and window references with globalThis for better compatibility
17
+ - ef2968a Updated scriptLoader, cookieDiscovery, cookieUtils, dataLayerEvents, developerGuidance, peerDepsCheck, scriptIntegrations, and scriptLoader files to use globalThis.document and globalThis.window.
18
+ - ef2968a Improved cookie handling functions to check for document and window availability using globalThis.
19
+ - ef2968a Enhanced tests to reference globalThis for consistency.
20
+ - ef2968a Cleaned up code formatting and comments for clarity.
21
+ - b04c00b Refactor coverage check script to use node imports.
22
+ - b04c00b Adjust TypeDoc script for ESM compatibility.
23
+ - 3af2fcb Fix path resolution in tsconfig for better module imports.
24
+
25
+ ### Testes
26
+ - b04c00b Implement tests for CookieBanner to verify rendering based on consent and debug mode.
27
+ - b04c00b Enhance FloatingPreferencesButton tests to check for localized text via props.
28
+ - b04c00b Extend PreferencesModal tests to cover temporary preference resets, active scripts rendering, and custom text application.
29
+
30
+ ### Documentação
31
+ - d430eef docs: atualizar instruções para agentes com visão geral do projeto e comandos essenciais
32
+ - d430eef Updated documentation to reflect changes in globalThis usage.
33
+ - d430eef Update API documentation to include new integration functions and ESM/CJS testing configurations.
34
+
35
+ - Updated dependencies [[`44b885b`](https://github.com/lucianoedipo/react-lgpd-consent/commit/44b885b7c81f1cb5822e2dcfde2975e69e8d4893)]:
36
+ - @react-lgpd-consent/core@0.7.2
37
+ - @react-lgpd-consent/mui@0.7.2
38
+
3
39
  ## 0.7.1
4
40
 
5
41
  ### Patch Changes
@@ -362,7 +398,7 @@
362
398
  - **Correção crítica**: `loadScript` agora aguarda dinamicamente o consentimento em vez de rejeitar imediatamente, permitindo que scripts carreguem quando preferências mudarem
363
399
  - Cleanup automático do registro ao completar/falhar carregamento
364
400
  - Adicionados testes extensivos: `ConsentScriptLoader.strictmode.test.tsx` e `scriptLoader.strictmode.test.ts`
365
- - Documentação completa em `docs/REACT19-STRICTMODE.md`
401
+ - Documentação completa em `REACT19-STRICTMODE.md`
366
402
  - Todos os 302 testes passando, incluindo 5 novos testes de StrictMode
367
403
 
368
404
  **Breaking Changes:** Nenhuma - totalmente retrocompatível
package/INTEGRACOES.md CHANGED
@@ -6,6 +6,12 @@ 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
+ ### ✅ Regras de Configuração (RN)
10
+
11
+ - **Categoria padrão com override**: cada integração define uma categoria padrão, mas o consumidor pode sobrescrever via `category` no config.
12
+ - **Config obrigatória**: se um campo obrigatório estiver vazio (ex.: `measurementId`, `containerId`, `pixelId`), a integração **não executa**. Em **dev** é logado erro; em **prod** não há log.
13
+ - **DataLayer**: se `globalThis.window.dataLayer` não existir, a biblioteca cria `[]`; se existir e tiver `push`, usa como está; se existir sem `push`, não sobrescreve e avisa em dev.
14
+
9
15
  ### ✨ Novidades v0.7.1
10
16
 
11
17
  - **🎯 Google Consent Mode v2 Automático**: GA4 e GTM agora implementam Consent Mode v2 automaticamente:
@@ -173,6 +179,7 @@ const integrations = [createUserWayIntegration({ accountId: 'USERWAY_ACCOUNT_ID'
173
179
  Para simplificar a configuração de múltiplas integrações, a biblioteca oferece templates e funções de ajuda.
174
180
 
175
181
  - `suggestCategoryForScript(name: string)`: Sugere a categoria LGPD apropriada para um nome de script conhecido.
182
+ - `createSuggestedIntegration(config)`: Cria integração customizada com categoria sugerida automaticamente (pode sobrescrever com `category`).
176
183
  - `createECommerceIntegrations`, `createSaaSIntegrations`, `createCorporateIntegrations`: Templates de negócio que agrupam as integrações mais comuns para cada setor.
177
184
  - `INTEGRATION_TEMPLATES`: Constante com presets de IDs e categorias para cada template.
178
185
 
@@ -201,6 +208,19 @@ function App() {
201
208
  }
202
209
  ```
203
210
 
211
+ ### Exemplo de integração sugerida (custom)
212
+
213
+ ```tsx
214
+ import { createSuggestedIntegration } from 'react-lgpd-consent'
215
+
216
+ const integrations = [
217
+ createSuggestedIntegration({
218
+ id: 'custom-chat',
219
+ src: 'https://example.com/chat.js',
220
+ }),
221
+ ]
222
+ ```
223
+
204
224
  ---
205
225
 
206
226
  ## 🔎 Descoberta Automática de Cookies (Experimental v0.4.1)
@@ -253,6 +273,12 @@ interface ScriptIntegration {
253
273
 
254
274
  A partir da versão **0.4.5**, a biblioteca dispara automaticamente eventos padronizados no `dataLayer` para facilitar rastreamento, auditoria LGPD e integrações com o Google Tag Manager.
255
275
 
276
+ ### Comportamento do `dataLayer`
277
+
278
+ - Se `globalThis.window.dataLayer` não existir, a biblioteca cria `[]`.
279
+ - Se existir e tiver `push`, o array/objeto é usado como está.
280
+ - Se existir sem `push`, a biblioteca não sobrescreve e avisa em dev.
281
+
256
282
  ### Eventos Disponíveis
257
283
 
258
284
  #### 1. `consent_initialized`
@@ -458,7 +484,7 @@ import { googleAnalytics4Integration } from './integrations'
458
484
  console.log('Mudança:', { current, previous })
459
485
 
460
486
  // Exemplo: disparar evento no dataLayer
461
- window.dataLayer?.push({
487
+ globalThis.window?.dataLayer?.push({
462
488
  event: 'consent_preferences_updated',
463
489
  consent_analytics: current.preferences.analytics,
464
490
  consent_marketing: current.preferences.marketing,
package/QUICKSTART.en.md CHANGED
@@ -273,13 +273,13 @@ function MyComponent() {
273
273
  }
274
274
  ```
275
275
 
276
- ### Global: `window.openPreferencesModal` (for plain JS)
276
+ ### Global: `globalThis.window.openPreferencesModal` (for plain JS)
277
277
 
278
278
  ```html
279
- <button onclick="window.openPreferencesModal?.()">Configure cookies</button>
279
+ <button onclick="globalThis.window?.openPreferencesModal?.()">Configure cookies</button>
280
280
 
281
281
  <script>
282
- if (typeof window.openPreferencesModal === 'function') {
282
+ if (typeof globalThis.window?.openPreferencesModal === 'function') {
283
283
  console.log('Consent system available')
284
284
  }
285
285
  </script>
package/QUICKSTART.md CHANGED
@@ -257,7 +257,13 @@ function BootstrapConsentMode() {
257
257
  React.useEffect(() => {
258
258
  const w = window as any
259
259
  w.dataLayer = w.dataLayer ?? []
260
- w.gtag = w.gtag ?? ((...args: any[]) => w.dataLayer.push(args))
260
+ w.gtag =
261
+ w.gtag ??
262
+ ((...args: any[]) => {
263
+ if (typeof w.dataLayer?.push === 'function') {
264
+ w.dataLayer.push(args)
265
+ }
266
+ })
261
267
  w.gtag('consent', 'default', {
262
268
  ad_storage: 'denied',
263
269
  ad_user_data: 'denied',
@@ -486,7 +492,11 @@ function ComplianceWrapper({ children }: { children: React.ReactNode }) {
486
492
  }}
487
493
  onConsentVersionChange={({ previousKey, nextKey, resetConsent }) => {
488
494
  console.info('[consent] versão atualizada', { previousKey, nextKey })
489
- window.dataLayer?.push({ event: 'consent_version_bumped', previousKey, nextKey })
495
+ globalThis.window?.dataLayer?.push({
496
+ event: 'consent_version_bumped',
497
+ previousKey,
498
+ nextKey,
499
+ })
490
500
  localStorage.removeItem('marketing-optins')
491
501
  resetConsent()
492
502
  }}
@@ -948,24 +958,24 @@ function MeuComponente() {
948
958
  }
949
959
  ```
950
960
 
951
- ### window.openPreferencesModal (JavaScript Puro)
961
+ ### globalThis.window.openPreferencesModal (JavaScript Puro)
952
962
 
953
963
  ```html
954
964
  <!-- Em templates HTML, emails ou widgets externos -->
955
- <button onclick="window.openPreferencesModal?.()">Configurar Cookies</button>
965
+ <button onclick="globalThis.window?.openPreferencesModal?.()">Configurar Cookies</button>
956
966
 
957
967
  <script>
958
968
  // Ou em JavaScript puro
959
969
  function abrirConfiguracoesCookies() {
960
- if (window.openPreferencesModal) {
961
- window.openPreferencesModal()
970
+ if (globalThis.window?.openPreferencesModal) {
971
+ globalThis.window.openPreferencesModal()
962
972
  } else {
963
973
  console.warn('Sistema de consentimento não carregado')
964
974
  }
965
975
  }
966
976
 
967
977
  // Verificar se função está disponível
968
- if (typeof window.openPreferencesModal === 'function') {
978
+ if (typeof globalThis.window?.openPreferencesModal === 'function') {
969
979
  console.log('✅ Sistema de consentimento disponível')
970
980
  }
971
981
  </script>
package/README.en.md CHANGED
@@ -76,7 +76,7 @@ function Analytics() {
76
76
  src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"
77
77
  strategy="afterInteractive"
78
78
  >
79
- {`window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'GA_MEASUREMENT_ID');`}
79
+ {`globalThis.window && (globalThis.window.dataLayer = globalThis.window.dataLayer || []); function gtag(){ if (typeof globalThis.window?.dataLayer?.push === 'function') { globalThis.window.dataLayer.push(arguments) } } gtag('js', new Date()); gtag('config', 'GA_MEASUREMENT_ID');`}
80
80
  </ConsentScriptLoader>
81
81
  )
82
82
  }
@@ -174,4 +174,3 @@ MIT © Luciano Edipo — see the `LICENSE` file.
174
174
  ---
175
175
 
176
176
  If you want the Portuguese README, see `README.md` in the same package.
177
-
package/README.md CHANGED
@@ -76,7 +76,7 @@ function Analytics() {
76
76
  src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"
77
77
  strategy="afterInteractive"
78
78
  >
79
- {`window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'GA_MEASUREMENT_ID');`}
79
+ {`globalThis.window && (globalThis.window.dataLayer = globalThis.window.dataLayer ?? []); function gtag(){ if (typeof globalThis.window?.dataLayer?.push === 'function') { globalThis.window.dataLayer.push(arguments) } } gtag('js', new Date()); gtag('config', 'GA_MEASUREMENT_ID');`}
80
80
  </ConsentScriptLoader>
81
81
  )
82
82
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-lgpd-consent",
3
- "version": "0.7.1",
3
+ "version": "0.7.2",
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.7.1",
98
- "@react-lgpd-consent/mui": "^0.7.1"
97
+ "@react-lgpd-consent/core": "^0.7.2",
98
+ "@react-lgpd-consent/mui": "^0.7.2"
99
99
  },
100
100
  "size-limit": [
101
101
  {