react-lgpd-consent 0.3.5 → 0.3.7

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/CHANGELOG.md CHANGED
@@ -4,7 +4,25 @@ Todas as mudanças notáveis neste projeto serão documentadas neste arquivo.
4
4
 
5
5
  O formato é baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.0.0/), e este projeto segue [Semantic Versioning](https://semver.org/lang/pt-BR/).
6
6
 
7
- ## [Unreleased]
7
+ ## [0.3.7] - 2025-09-08 - Testes de UI e carregamento de scripts
8
+
9
+ ### 🧪 Novos testes e cobertura
10
+
11
+ - CookieBanner
12
+ - Testes para renderização condicional em modos bloqueante (overlay) e não-bloqueante (Snackbar)
13
+ - Verificação de abertura do modal ao clicar em “Preferências” e persistência ao clicar em “Recusar”
14
+ - ConsentScriptLoader / Hook
15
+ - Gating por consentimento e categoria; não carrega scripts quando não consentido ou categoria desabilitada
16
+ - Tratamento de erros (log `logger.error` quando `loadScript` rejeita)
17
+ - `reloadOnChange` reexecuta o carregamento ao reabilitar a categoria; default não recarrega
18
+ - Integrações de script
19
+ - Verificação de `attrs` em integrações (GA define `async: 'true'`)
20
+
21
+ ### 🔧 Interno
22
+
23
+ - Aumento da estabilidade para refatorações futuras na camada de UI e utilitários de carregamento.
24
+
25
+ ## [0.3.6] - 2025-08-28 - Correção crítica: Herança de ThemeProvider
8
26
 
9
27
  ### ✨ Novas funcionalidades e melhorias
10
28
 
@@ -46,20 +64,16 @@ O formato é baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.0.
46
64
  - Novo Quickstart em PT/EN e simplificações no `README` com foco em `QUICKSTART`.
47
65
  - Documentação de uso do Storybook e troubleshooting adicionada em `docs`.
48
66
 
49
- ### 🛠️ Correção crítica: Herança de ThemeProvider (v0.3.5)
67
+ ### 🛠️ Correção crítica
50
68
 
51
- - **Corrigido:** A biblioteca não deve criar ou impor um `ThemeProvider` global por si só. Agora o `ConsentProvider` herda o theme do app consumidor quando um `ThemeProvider` do MUI estiver presente. O Provider só envolverá com `ThemeProvider` se a prop `theme` for explicitamente fornecida.
69
+ - **Corrigido:** A biblioteca não deve criar ou impor um `ThemeProvider` global por si só. O `ConsentProvider` agora herda o theme do app consumidor quando um `ThemeProvider` do MUI estiver presente. O Provider só envolverá com `ThemeProvider` se a prop `theme` for explicitamente fornecida.
52
70
  - **Motivação:** Evitar conflitos de contexto MUI/Emotion, regressões visuais e problemas em SSR causados por criação de tema no escopo de módulo.
53
- - **Export:** `createDefaultConsentTheme()` foi adicionada como fábrica para quem precisar de um fallback explícito. também um getter compat (deprecated) `defaultConsentTheme()` que retorna uma nova instância quando chamada.
54
- - **Compatibilidade:** Uso padrão continua igual — se seu app fornece um `ThemeProvider` e você passa o mesmo theme para `ConsentProvider` (ou não passa `theme`), tudo continuará funcionando normalmente.
55
-
56
- Referência: issues/PR relacionadas e notas de release serão adicionadas no branch de release.
71
+ - **Export:** `createDefaultConsentTheme()` foi adicionada como fábrica para quem precisar de um fallback explícito. Mantemos também um getter de compatibilidade (deprecated) `defaultConsentTheme()` que retorna uma nova instância quando chamada, evitando side-effects no import.
72
+ - **Compatibilidade:** Uso padrão continua igual — se seu app fornece um `ThemeProvider` o `ConsentProvider` usará o theme existente. Para quem precisa de um fallback explícito, passe `theme={createDefaultConsentTheme()}` ao `ConsentProvider`.
57
73
 
58
- ### ♻️ Dependências e manutenção
74
+ > Nota: originalmente essa correção foi marcada como v0.3.5; devido a conflito de publicação a versão foi bumpada localmente para v0.3.6 e a entrada foi gravada nesta release.
59
75
 
60
- - Dev-deps e chores
61
- - Atualizações de dependências de desenvolvimento (ex.: `jest`, `@types/jest`, `typedoc`, `jest-environment-jsdom`) e ajustes na `package.json` (engine `npm` atualizado, scripts e chores relacionados ao Storybook).
62
- - Limpeza de arquivos redundantes e ajustes de ESLint/preview para Storybook.
76
+ - Limpeza de arquivos redundantes e ajustes de ESLint/preview para Storybook.
63
77
 
64
78
  ### Commits representativos
65
79
 
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  PreferencesModal
3
- } from "./chunk-MHCQFGRJ.js";
3
+ } from "./chunk-TKN3PNIW.js";
4
4
  export {
5
5
  PreferencesModal
6
6
  };
@@ -87,9 +87,10 @@ function analyzeDeveloperConfiguration(config) {
87
87
  return guidance;
88
88
  }
89
89
  function logDeveloperGuidance(guidance, disableGuidanceProp) {
90
- const nodeEnv = typeof globalThis.process !== "undefined" ? globalThis.process.env?.NODE_ENV : void 0;
91
- const isProd = nodeEnv === "production" || globalThis.__LGPD_PRODUCTION__ === true && typeof globalThis !== "undefined";
92
- const isDisabled = !!disableGuidanceProp || globalThis.__LGPD_DISABLE_GUIDANCE__ === true && typeof globalThis !== "undefined";
90
+ const gt = globalThis;
91
+ const nodeEnv = typeof gt.process !== "undefined" ? gt.process?.env?.NODE_ENV : void 0;
92
+ const isProd = nodeEnv === "production" || gt.__LGPD_PRODUCTION__ === true;
93
+ const isDisabled = !!disableGuidanceProp || gt.__LGPD_DISABLE_GUIDANCE__ === true;
93
94
  if (isProd || isDisabled) return;
94
95
  const PREFIX = "[\u{1F36A} LGPD-CONSENT]";
95
96
  if (guidance.warnings.length > 0) {
@@ -217,7 +218,7 @@ var _ConsentLogger = class _ConsentLogger {
217
218
  }
218
219
  /**
219
220
  * Registra uma mensagem de erro.
220
- * @param {...any[]} args Os argumentos a serem logados.
221
+ * @param {...unknown[]} args Argumentos a serem logados.
221
222
  */
222
223
  error(...args) {
223
224
  if (this.enabled && this.level >= 0 /* ERROR */) {
@@ -226,7 +227,7 @@ var _ConsentLogger = class _ConsentLogger {
226
227
  }
227
228
  /**
228
229
  * Registra uma mensagem de aviso.
229
- * @param {...any[]} args Os argumentos a serem logados.
230
+ * @param {...unknown[]} args Argumentos a serem logados.
230
231
  */
231
232
  warn(...args) {
232
233
  if (this.enabled && this.level >= 1 /* WARN */) {
@@ -235,7 +236,7 @@ var _ConsentLogger = class _ConsentLogger {
235
236
  }
236
237
  /**
237
238
  * Registra uma mensagem informativa.
238
- * @param {...any[]} args Os argumentos a serem logados.
239
+ * @param {...unknown[]} args Argumentos a serem logados.
239
240
  */
240
241
  info(...args) {
241
242
  if (this.enabled && this.level >= 2 /* INFO */) {
@@ -244,7 +245,7 @@ var _ConsentLogger = class _ConsentLogger {
244
245
  }
245
246
  /**
246
247
  * Registra uma mensagem de depuração.
247
- * @param {...any[]} args Os argumentos a serem logados.
248
+ * @param {...unknown[]} args Argumentos a serem logados.
248
249
  */
249
250
  debug(...args) {
250
251
  if (this.enabled && this.level >= 3 /* DEBUG */) {
@@ -253,7 +254,7 @@ var _ConsentLogger = class _ConsentLogger {
253
254
  }
254
255
  /**
255
256
  * Inicia um grupo de logs no console.
256
- * @param {...any[]} args Os argumentos para o título do grupo.
257
+ * @param {...unknown[]} args Argumentos para o título do grupo.
257
258
  */
258
259
  group(...args) {
259
260
  if (this.enabled && this.level >= 3 /* DEBUG */) {
@@ -270,8 +271,8 @@ var _ConsentLogger = class _ConsentLogger {
270
271
  }
271
272
  /**
272
273
  * Exibe dados tabulares no console.
273
- * @param {any} tabularData Os dados a serem exibidos na tabela.
274
- * @param {string[]} [properties] Um array opcional de propriedades para exibir.
274
+ * @param {unknown} tabularData Dados a serem exibidos na tabela.
275
+ * @param {string[]} [properties] Propriedades opcionais para exibir.
275
276
  */
276
277
  table(tabularData, properties) {
277
278
  if (this.enabled && this.level >= 3 /* DEBUG */) {
@@ -280,21 +281,27 @@ var _ConsentLogger = class _ConsentLogger {
280
281
  }
281
282
  /**
282
283
  * Registra informações sobre a compatibilidade do tema Material-UI.
283
- * @param {any} themeInfo Objeto com informações do tema.
284
+ * @param {unknown} themeInfo Objeto potencialmente parcial do tema (inspeção segura).
284
285
  */
285
286
  themeCompatibility(themeInfo) {
287
+ const isRecord = (v) => typeof v === "object" && v !== null;
288
+ const theme = isRecord(themeInfo) ? themeInfo : void 0;
289
+ const palette = theme && isRecord(theme["palette"]) ? theme["palette"] : void 0;
290
+ const primary = palette && isRecord(palette["primary"]);
291
+ const transitions = theme && isRecord(theme["transitions"]) ? theme["transitions"] : void 0;
292
+ const duration = transitions && isRecord(transitions["duration"]);
286
293
  this.debug("Theme compatibility check:", {
287
- hasTheme: !!themeInfo,
288
- hasPalette: !!themeInfo?.palette,
289
- hasPrimary: !!themeInfo?.palette?.primary,
290
- hasTransitions: !!themeInfo?.transitions,
291
- hasDuration: !!themeInfo?.transitions?.duration
294
+ hasTheme: !!theme,
295
+ hasPalette: !!palette,
296
+ hasPrimary: !!primary,
297
+ hasTransitions: !!transitions,
298
+ hasDuration: !!duration
292
299
  });
293
300
  }
294
301
  /**
295
302
  * Registra mudanças no estado de consentimento.
296
- * @param {string} action A ação que causou a mudança de estado.
297
- * @param {any} state O estado atual do consentimento.
303
+ * @param {string} action Ação que causou a mudança de estado.
304
+ * @param {{ consented?: boolean; isModalOpen?: boolean; preferences?: Record<string, unknown> }} state Estado atual.
298
305
  */
299
306
  consentState(action, state) {
300
307
  this.debug(`Consent state change [${action}]:`, {
@@ -305,9 +312,9 @@ var _ConsentLogger = class _ConsentLogger {
305
312
  }
306
313
  /**
307
314
  * Registra operações de cookie (leitura, escrita, remoção).
308
- * @param {'read' | 'write' | 'delete'} operation O tipo de operação de cookie.
309
- * @param {string} cookieName O nome do cookie.
310
- * @param {any} [data] Os dados do cookie, se aplicável.
315
+ * @param {'read' | 'write' | 'delete'} operation Tipo de operação.
316
+ * @param {string} cookieName Nome do cookie.
317
+ * @param {unknown} [data] Dados associados, se aplicável.
311
318
  */
312
319
  cookieOperation(operation, cookieName, data) {
313
320
  this.debug(`Cookie ${operation}:`, {
@@ -318,8 +325,8 @@ var _ConsentLogger = class _ConsentLogger {
318
325
  }
319
326
  /**
320
327
  * Registra a renderização de um componente.
321
- * @param {string} componentName O nome do componente.
322
- * @param {any} [props] As propriedades do componente.
328
+ * @param {string} componentName Nome do componente.
329
+ * @param {Record<string, unknown>} [props] Propriedades do componente.
323
330
  */
324
331
  componentRender(componentName, props) {
325
332
  this.debug(`Component render [${componentName}]:`, {
@@ -338,8 +345,8 @@ var _ConsentLogger = class _ConsentLogger {
338
345
  }
339
346
  /**
340
347
  * Registra chamadas à API interna da biblioteca.
341
- * @param {string} method O nome do método da API chamado.
342
- * @param {any} [params] Os parâmetros passados para o método.
348
+ * @param {string} method Nome do método da API chamado.
349
+ * @param {unknown} [params] Parâmetros passados para o método.
343
350
  */
344
351
  apiUsage(method, params) {
345
352
  this.debug(`API call [${method}]:`, params);
@@ -397,8 +404,8 @@ function migrateLegacyCookie(legacyData) {
397
404
  const now = (/* @__PURE__ */ new Date()).toISOString();
398
405
  return {
399
406
  version: COOKIE_SCHEMA_VERSION,
400
- consented: legacyData.consented || false,
401
- preferences: legacyData.preferences || { necessary: true },
407
+ consented: Boolean(legacyData.consented) || false,
408
+ preferences: legacyData.preferences && typeof legacyData.preferences === "object" ? legacyData.preferences : { necessary: true },
402
409
  consentDate: now,
403
410
  lastUpdate: now,
404
411
  source: "banner",
@@ -848,7 +855,7 @@ function FloatingPreferencesButton({
848
855
  // src/context/ConsentContext.tsx
849
856
  import { jsx as jsx6, jsxs as jsxs3 } from "react/jsx-runtime";
850
857
  var PreferencesModal = React4.lazy(
851
- () => import("./PreferencesModal-KAZMVPBD.js").then((m) => ({
858
+ () => import("./PreferencesModal-3KKTKVII.js").then((m) => ({
852
859
  default: m.PreferencesModal
853
860
  }))
854
861
  );
@@ -1142,12 +1149,17 @@ function ConsentProvider({
1142
1149
  }
1143
1150
  ) : (
1144
1151
  // Encaminha `floatingPreferencesButtonProps` para o componente padrão
1145
- /* @__PURE__ */ jsx6(FloatingPreferencesButton, { ...floatingPreferencesButtonProps })
1152
+ /* @__PURE__ */ jsx6(
1153
+ FloatingPreferencesButton,
1154
+ {
1155
+ ...floatingPreferencesButtonProps ?? {}
1156
+ }
1157
+ )
1146
1158
  ))
1147
1159
  ]
1148
1160
  }
1149
1161
  ) }) }) }) }) });
1150
- if (theme) {
1162
+ if (mergedTheme) {
1151
1163
  return /* @__PURE__ */ jsx6(ThemeProvider, { theme: mergedTheme, children: content });
1152
1164
  }
1153
1165
  return content;
package/dist/index.cjs CHANGED
@@ -100,9 +100,10 @@ function analyzeDeveloperConfiguration(config) {
100
100
  return guidance;
101
101
  }
102
102
  function logDeveloperGuidance(guidance, disableGuidanceProp) {
103
- const nodeEnv = typeof globalThis.process !== "undefined" ? globalThis.process.env?.NODE_ENV : void 0;
104
- const isProd = nodeEnv === "production" || globalThis.__LGPD_PRODUCTION__ === true && typeof globalThis !== "undefined";
105
- const isDisabled = !!disableGuidanceProp || globalThis.__LGPD_DISABLE_GUIDANCE__ === true && typeof globalThis !== "undefined";
103
+ const gt = globalThis;
104
+ const nodeEnv = typeof gt.process !== "undefined" ? gt.process?.env?.NODE_ENV : void 0;
105
+ const isProd = nodeEnv === "production" || gt.__LGPD_PRODUCTION__ === true;
106
+ const isDisabled = !!disableGuidanceProp || gt.__LGPD_DISABLE_GUIDANCE__ === true;
106
107
  if (isProd || isDisabled) return;
107
108
  const PREFIX = "[\u{1F36A} LGPD-CONSENT]";
108
109
  if (guidance.warnings.length > 0) {
@@ -250,7 +251,7 @@ var init_logger = __esm({
250
251
  }
251
252
  /**
252
253
  * Registra uma mensagem de erro.
253
- * @param {...any[]} args Os argumentos a serem logados.
254
+ * @param {...unknown[]} args Argumentos a serem logados.
254
255
  */
255
256
  error(...args) {
256
257
  if (this.enabled && this.level >= 0 /* ERROR */) {
@@ -259,7 +260,7 @@ var init_logger = __esm({
259
260
  }
260
261
  /**
261
262
  * Registra uma mensagem de aviso.
262
- * @param {...any[]} args Os argumentos a serem logados.
263
+ * @param {...unknown[]} args Argumentos a serem logados.
263
264
  */
264
265
  warn(...args) {
265
266
  if (this.enabled && this.level >= 1 /* WARN */) {
@@ -268,7 +269,7 @@ var init_logger = __esm({
268
269
  }
269
270
  /**
270
271
  * Registra uma mensagem informativa.
271
- * @param {...any[]} args Os argumentos a serem logados.
272
+ * @param {...unknown[]} args Argumentos a serem logados.
272
273
  */
273
274
  info(...args) {
274
275
  if (this.enabled && this.level >= 2 /* INFO */) {
@@ -277,7 +278,7 @@ var init_logger = __esm({
277
278
  }
278
279
  /**
279
280
  * Registra uma mensagem de depuração.
280
- * @param {...any[]} args Os argumentos a serem logados.
281
+ * @param {...unknown[]} args Argumentos a serem logados.
281
282
  */
282
283
  debug(...args) {
283
284
  if (this.enabled && this.level >= 3 /* DEBUG */) {
@@ -286,7 +287,7 @@ var init_logger = __esm({
286
287
  }
287
288
  /**
288
289
  * Inicia um grupo de logs no console.
289
- * @param {...any[]} args Os argumentos para o título do grupo.
290
+ * @param {...unknown[]} args Argumentos para o título do grupo.
290
291
  */
291
292
  group(...args) {
292
293
  if (this.enabled && this.level >= 3 /* DEBUG */) {
@@ -303,8 +304,8 @@ var init_logger = __esm({
303
304
  }
304
305
  /**
305
306
  * Exibe dados tabulares no console.
306
- * @param {any} tabularData Os dados a serem exibidos na tabela.
307
- * @param {string[]} [properties] Um array opcional de propriedades para exibir.
307
+ * @param {unknown} tabularData Dados a serem exibidos na tabela.
308
+ * @param {string[]} [properties] Propriedades opcionais para exibir.
308
309
  */
309
310
  table(tabularData, properties) {
310
311
  if (this.enabled && this.level >= 3 /* DEBUG */) {
@@ -313,21 +314,27 @@ var init_logger = __esm({
313
314
  }
314
315
  /**
315
316
  * Registra informações sobre a compatibilidade do tema Material-UI.
316
- * @param {any} themeInfo Objeto com informações do tema.
317
+ * @param {unknown} themeInfo Objeto potencialmente parcial do tema (inspeção segura).
317
318
  */
318
319
  themeCompatibility(themeInfo) {
320
+ const isRecord = (v) => typeof v === "object" && v !== null;
321
+ const theme = isRecord(themeInfo) ? themeInfo : void 0;
322
+ const palette = theme && isRecord(theme["palette"]) ? theme["palette"] : void 0;
323
+ const primary = palette && isRecord(palette["primary"]);
324
+ const transitions = theme && isRecord(theme["transitions"]) ? theme["transitions"] : void 0;
325
+ const duration = transitions && isRecord(transitions["duration"]);
319
326
  this.debug("Theme compatibility check:", {
320
- hasTheme: !!themeInfo,
321
- hasPalette: !!themeInfo?.palette,
322
- hasPrimary: !!themeInfo?.palette?.primary,
323
- hasTransitions: !!themeInfo?.transitions,
324
- hasDuration: !!themeInfo?.transitions?.duration
327
+ hasTheme: !!theme,
328
+ hasPalette: !!palette,
329
+ hasPrimary: !!primary,
330
+ hasTransitions: !!transitions,
331
+ hasDuration: !!duration
325
332
  });
326
333
  }
327
334
  /**
328
335
  * Registra mudanças no estado de consentimento.
329
- * @param {string} action A ação que causou a mudança de estado.
330
- * @param {any} state O estado atual do consentimento.
336
+ * @param {string} action Ação que causou a mudança de estado.
337
+ * @param {{ consented?: boolean; isModalOpen?: boolean; preferences?: Record<string, unknown> }} state Estado atual.
331
338
  */
332
339
  consentState(action, state) {
333
340
  this.debug(`Consent state change [${action}]:`, {
@@ -338,9 +345,9 @@ var init_logger = __esm({
338
345
  }
339
346
  /**
340
347
  * Registra operações de cookie (leitura, escrita, remoção).
341
- * @param {'read' | 'write' | 'delete'} operation O tipo de operação de cookie.
342
- * @param {string} cookieName O nome do cookie.
343
- * @param {any} [data] Os dados do cookie, se aplicável.
348
+ * @param {'read' | 'write' | 'delete'} operation Tipo de operação.
349
+ * @param {string} cookieName Nome do cookie.
350
+ * @param {unknown} [data] Dados associados, se aplicável.
344
351
  */
345
352
  cookieOperation(operation, cookieName, data) {
346
353
  this.debug(`Cookie ${operation}:`, {
@@ -351,8 +358,8 @@ var init_logger = __esm({
351
358
  }
352
359
  /**
353
360
  * Registra a renderização de um componente.
354
- * @param {string} componentName O nome do componente.
355
- * @param {any} [props] As propriedades do componente.
361
+ * @param {string} componentName Nome do componente.
362
+ * @param {Record<string, unknown>} [props] Propriedades do componente.
356
363
  */
357
364
  componentRender(componentName, props) {
358
365
  this.debug(`Component render [${componentName}]:`, {
@@ -371,8 +378,8 @@ var init_logger = __esm({
371
378
  }
372
379
  /**
373
380
  * Registra chamadas à API interna da biblioteca.
374
- * @param {string} method O nome do método da API chamado.
375
- * @param {any} [params] Os parâmetros passados para o método.
381
+ * @param {string} method Nome do método da API chamado.
382
+ * @param {unknown} [params] Parâmetros passados para o método.
376
383
  */
377
384
  apiUsage(method, params) {
378
385
  this.debug(`API call [${method}]:`, params);
@@ -419,8 +426,8 @@ function migrateLegacyCookie(legacyData) {
419
426
  const now = (/* @__PURE__ */ new Date()).toISOString();
420
427
  return {
421
428
  version: COOKIE_SCHEMA_VERSION,
422
- consented: legacyData.consented || false,
423
- preferences: legacyData.preferences || { necessary: true },
429
+ consented: Boolean(legacyData.consented) || false,
430
+ preferences: legacyData.preferences && typeof legacyData.preferences === "object" ? legacyData.preferences : { necessary: true },
424
431
  consentDate: now,
425
432
  lastUpdate: now,
426
433
  source: "banner",
@@ -1169,12 +1176,17 @@ function ConsentProvider({
1169
1176
  }
1170
1177
  ) : (
1171
1178
  // Encaminha `floatingPreferencesButtonProps` para o componente padrão
1172
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(FloatingPreferencesButton, { ...floatingPreferencesButtonProps })
1179
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1180
+ FloatingPreferencesButton,
1181
+ {
1182
+ ...floatingPreferencesButtonProps ?? {}
1183
+ }
1184
+ )
1173
1185
  ))
1174
1186
  ]
1175
1187
  }
1176
1188
  ) }) }) }) }) });
1177
- if (theme) {
1189
+ if (mergedTheme) {
1178
1190
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_styles2.ThemeProvider, { theme: mergedTheme, children: content });
1179
1191
  }
1180
1192
  return content;
@@ -1592,13 +1604,7 @@ function ConsentScriptLoader({
1592
1604
  const alreadyLoaded = loadedScripts.current.has(integration.id);
1593
1605
  if (shouldLoad && (!alreadyLoaded || reloadOnChange)) {
1594
1606
  try {
1595
- await loadScript(
1596
- integration.id,
1597
- integration.src,
1598
- integration.category,
1599
- // Categoria dinâmica
1600
- integration.attrs
1601
- );
1607
+ await loadScript(integration.id, integration.src, integration.category, integration.attrs);
1602
1608
  if (integration.init) {
1603
1609
  integration.init();
1604
1610
  }
@@ -1627,13 +1633,7 @@ function useConsentScriptLoader() {
1627
1633
  return false;
1628
1634
  }
1629
1635
  try {
1630
- await loadScript(
1631
- integration.id,
1632
- integration.src,
1633
- integration.category,
1634
- // Categoria dinâmica
1635
- integration.attrs
1636
- );
1636
+ await loadScript(integration.id, integration.src, integration.category, integration.attrs);
1637
1637
  if (integration.init) {
1638
1638
  integration.init();
1639
1639
  }
@@ -1655,14 +1655,14 @@ function createGoogleAnalyticsIntegration(config) {
1655
1655
  src: `https://www.googletagmanager.com/gtag/js?id=${config.measurementId}`,
1656
1656
  init: () => {
1657
1657
  if (typeof window !== "undefined") {
1658
- let gtag2 = function(...args) {
1659
- window.dataLayer.push(...args);
1658
+ const w = window;
1659
+ w.dataLayer = w.dataLayer ?? [];
1660
+ const gtag = (...args) => {
1661
+ w.dataLayer.push(...args);
1660
1662
  };
1661
- var gtag = gtag2;
1662
- window.dataLayer = window.dataLayer || [];
1663
- window.gtag = gtag2;
1664
- gtag2("js", /* @__PURE__ */ new Date());
1665
- gtag2("config", config.measurementId, config.config || {});
1663
+ w.gtag = gtag;
1664
+ gtag("js", /* @__PURE__ */ new Date());
1665
+ gtag("config", config.measurementId, config.config ?? {});
1666
1666
  }
1667
1667
  },
1668
1668
  attrs: { async: "true" }
@@ -1676,8 +1676,10 @@ function createGoogleTagManagerIntegration(config) {
1676
1676
  init: () => {
1677
1677
  if (typeof window !== "undefined") {
1678
1678
  const dataLayerName = config.dataLayerName || "dataLayer";
1679
- window[dataLayerName] = window[dataLayerName] || [];
1680
- window[dataLayerName].push({
1679
+ const w = window;
1680
+ const layer = w[dataLayerName] ?? [];
1681
+ w[dataLayerName] = layer;
1682
+ layer.push({
1681
1683
  "gtm.start": (/* @__PURE__ */ new Date()).getTime(),
1682
1684
  event: "gtm.js"
1683
1685
  });
@@ -1692,8 +1694,9 @@ function createUserWayIntegration(config) {
1692
1694
  src: "https://cdn.userway.org/widget.js",
1693
1695
  init: () => {
1694
1696
  if (typeof window !== "undefined") {
1695
- window.UserWayWidgetApp = window.UserWayWidgetApp || {};
1696
- window.UserWayWidgetApp.accountId = config.accountId;
1697
+ const w = window;
1698
+ w.UserWayWidgetApp = w.UserWayWidgetApp || {};
1699
+ w.UserWayWidgetApp.accountId = config.accountId;
1697
1700
  }
1698
1701
  },
1699
1702
  attrs: { "data-account": config.accountId }
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { DialogProps } from '@mui/material/Dialog';
3
- import * as React$1 from 'react';
4
3
  import { Theme } from '@mui/material/styles';
4
+ import * as React$1 from 'react';
5
5
  import { PaperProps } from '@mui/material/Paper';
6
6
  import { SnackbarProps } from '@mui/material/Snackbar';
7
7
  import { FabProps } from '@mui/material/Fab';
@@ -653,18 +653,23 @@ interface ConsentProviderProps {
653
653
  */
654
654
  texts?: Partial<ConsentTexts>;
655
655
  /**
656
- * Tema customizado Material-UI aplicado aos componentes.
657
- * Aceita qualquer objeto que será passado para ThemeProvider.
656
+ * Tema Material-UI a ser aplicado aos componentes via ThemeProvider.
657
+ *
658
+ * Observação importante: a biblioteca NÃO cria/mescla tema automaticamente.
659
+ * Se você fornecer um `theme` aqui, ele será repassado diretamente ao `ThemeProvider`.
660
+ * Se não fornecer, a lib não envolverá com `ThemeProvider` e herdará o tema do app.
658
661
  *
659
662
  * @example
660
663
  * ```tsx
661
- * theme={{
662
- * palette: { primary: { main: '#1976d2' } },
663
- * components: { MuiButton: { styleOverrides: { root: { borderRadius: 8 } } } }
664
- * }}
664
+ * import { createTheme } from '@mui/material/styles'
665
+ * const appTheme = createTheme({ palette: { primary: { main: '#1976d2' } } })
666
+ *
667
+ * <ConsentProvider theme={appTheme}>
668
+ * <App />
669
+ * </ConsentProvider>
665
670
  * ```
666
671
  */
667
- theme?: any;
672
+ theme?: Theme;
668
673
  /**
669
674
  * Tokens de design para customização visual avançada.
670
675
  * Oferece controle direto sobre cores, fontes, espaçamento e layout.
@@ -684,24 +689,24 @@ interface ConsentProviderProps {
684
689
  * Deve implementar a lógica de consentimento usando as props definidas em `CustomPreferencesModalProps`.
685
690
  */
686
691
  PreferencesModalComponent?: React.ComponentType<CustomPreferencesModalProps>;
687
- /** Props adicionais passadas para o modal customizado. */
688
- preferencesModalProps?: Record<string, any>;
692
+ /** Props adicionais passadas para o modal customizado (repassadas sem transformação). */
693
+ preferencesModalProps?: Record<string, unknown>;
689
694
  /**
690
695
  * Componente customizado para substituir o banner padrão de cookies.
691
696
  * Se não fornecido, o `CookieBanner` padrão será renderizado.
692
697
  * Deve implementar a lógica de consentimento usando as props definidas em `CustomCookieBannerProps`.
693
698
  */
694
699
  CookieBannerComponent?: React.ComponentType<CustomCookieBannerProps>;
695
- /** Props adicionais passadas para o banner customizado. */
696
- cookieBannerProps?: Record<string, any>;
700
+ /** Props adicionais passadas para o banner customizado (repassadas sem transformação). */
701
+ cookieBannerProps?: Record<string, unknown>;
697
702
  /**
698
703
  * Componente customizado para substituir o botão flutuante de preferências.
699
704
  * Se não fornecido, o `FloatingPreferencesButton` padrão será renderizado.
700
705
  * Deve implementar a lógica de consentimento usando as props definidas em `CustomFloatingPreferencesButtonProps`.
701
706
  */
702
707
  FloatingPreferencesButtonComponent?: React.ComponentType<CustomFloatingPreferencesButtonProps>;
703
- /** Props adicionais passadas para o botão flutuante customizado. */
704
- floatingPreferencesButtonProps?: Record<string, any>;
708
+ /** Props adicionais passadas para o botão flutuante customizado (repassadas sem transformação). */
709
+ floatingPreferencesButtonProps?: Record<string, unknown>;
705
710
  /**
706
711
  * Desabilita o botão flutuante de preferências.
707
712
  * Útil quando o usuário da lib quer ter controle total sobre o acesso às preferências.
@@ -1600,7 +1605,7 @@ declare function ConsentGate(props: Readonly<{
1600
1605
  *
1601
1606
  * @param {string} id Um identificador único para o elemento `<script>` a ser criado.
1602
1607
  * @param {string} src A URL do script externo a ser carregado.
1603
- * @param {'analytics' | 'marketing' | null} [category=null] A categoria de consentimento exigida para o script. Se o consentimento para esta categoria não for dado, o script não será carregado.
1608
+ * @param {import('../types/types').Category | null} [category=null] A categoria de consentimento exigida para o script. Se o consentimento para esta categoria não for dado, o script não será carregado.
1604
1609
  * @param {Record<string, string>} [attrs={}] Atributos adicionais a serem aplicados ao elemento `<script>` (ex: `{ async: 'true' }`).
1605
1610
  * @returns {Promise<void>} Uma Promise que resolve quando o script é carregado com sucesso, ou rejeita se o consentimento não for dado ou ocorrer um erro de carregamento.
1606
1611
  * @example
@@ -1611,7 +1616,8 @@ declare function ConsentGate(props: Readonly<{
1611
1616
  * .catch(error => console.error('Erro ao carregar script:', error))
1612
1617
  * ```
1613
1618
  */
1614
- declare function loadScript(id: string, src: string, category?: 'analytics' | 'marketing' | null, attrs?: Record<string, string>): Promise<void>;
1619
+
1620
+ declare function loadScript(id: string, src: string, category?: Category | null, attrs?: Record<string, string>): Promise<void>;
1615
1621
 
1616
1622
  /**
1617
1623
  * @constant
@@ -1637,13 +1643,19 @@ declare const defaultConsentTheme: () => Theme;
1637
1643
 
1638
1644
  /**
1639
1645
  * @interface ScriptIntegration
1640
- * Define a estrutura de um objeto de integração de script, usado para carregar scripts de terceiros condicionalmente.
1646
+ * Estrutura de uma integração de script de terceiros a ser carregada condicionalmente conforme o consentimento.
1647
+ *
1648
+ * @remarks
1649
+ * - `category` é um `Category` tipado (ex.: 'analytics', 'marketing').
1650
+ * - `init` roda após o script ser inserido no DOM e carregado.
1651
+ * - `attrs` é repassado como atributos HTML da tag `<script>`.
1641
1652
  */
1653
+
1642
1654
  interface ScriptIntegration {
1643
1655
  /** Um ID único para esta integração de script. */
1644
1656
  id: string;
1645
- /** A categoria de consentimento necessária para que este script seja carregado (ex: 'analytics', 'marketing'). */
1646
- category: string;
1657
+ /** Categoria de consentimento necessária para carregar o script. */
1658
+ category: Category;
1647
1659
  /** A URL do script a ser carregado. */
1648
1660
  src: string;
1649
1661
  /** Uma função opcional a ser executada após o script ser carregado e inicializado no DOM. */
@@ -1658,8 +1670,8 @@ interface ScriptIntegration {
1658
1670
  interface GoogleAnalyticsConfig {
1659
1671
  /** O ID de medição do GA4 (ex: 'G-XXXXXXXXXX'). */
1660
1672
  measurementId: string;
1661
- /** Um objeto opcional de configuração adicional a ser passado para o comando `gtag('config')`. */
1662
- config?: any;
1673
+ /** Objeto opcional repassado para `gtag('config')`. */
1674
+ config?: Record<string, unknown>;
1663
1675
  }
1664
1676
  /**
1665
1677
  * @interface GoogleTagManagerConfig
@@ -1683,30 +1695,30 @@ interface UserWayConfig {
1683
1695
  * @function
1684
1696
  * @category Utils
1685
1697
  * @since 0.2.0
1686
- * Cria um objeto de integração para o Google Analytics 4 (GA4).
1698
+ * Cria uma integração para Google Analytics 4 (GA4).
1687
1699
  *
1688
- * @param {GoogleAnalyticsConfig} config A configuração do GA4, incluindo o `measurementId`.
1689
- * @returns {ScriptIntegration} Um objeto `ScriptIntegration` configurado para o GA4.
1700
+ * @param {GoogleAnalyticsConfig} config Configuração com `measurementId` e `config` opcional.
1701
+ * @returns {ScriptIntegration} Integração tipada com `category: 'analytics'`.
1690
1702
  */
1691
1703
  declare function createGoogleAnalyticsIntegration(config: GoogleAnalyticsConfig): ScriptIntegration;
1692
1704
  /**
1693
1705
  * @function
1694
1706
  * @category Utils
1695
1707
  * @since 0.2.0
1696
- * Cria um objeto de integração para o Google Tag Manager (GTM).
1708
+ * Cria uma integração para Google Tag Manager (GTM).
1697
1709
  *
1698
- * @param {GoogleTagManagerConfig} config A configuração do GTM, incluindo o `containerId`.
1699
- * @returns {ScriptIntegration} Um objeto `ScriptIntegration` configurado para o GTM.
1710
+ * @param {GoogleTagManagerConfig} config Configuração com `containerId` e `dataLayerName` opcional.
1711
+ * @returns {ScriptIntegration} Integração tipada com `category: 'analytics'`.
1700
1712
  */
1701
1713
  declare function createGoogleTagManagerIntegration(config: GoogleTagManagerConfig): ScriptIntegration;
1702
1714
  /**
1703
1715
  * @function
1704
1716
  * @category Utils
1705
1717
  * @since 0.2.0
1706
- * Cria um objeto de integração para o widget de acessibilidade UserWay.
1718
+ * Cria uma integração para o widget de acessibilidade UserWay.
1707
1719
  *
1708
- * @param {UserWayConfig} config A configuração do UserWay, incluindo o `accountId`.
1709
- * @returns {ScriptIntegration} Um objeto `ScriptIntegration` configurado para o UserWay.
1720
+ * @param {UserWayConfig} config Configuração com `accountId`.
1721
+ * @returns {ScriptIntegration} Integração tipada com `category: 'functional'`.
1710
1722
  */
1711
1723
  declare function createUserWayIntegration(config: UserWayConfig): ScriptIntegration;
1712
1724
  /**
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { DialogProps } from '@mui/material/Dialog';
3
- import * as React$1 from 'react';
4
3
  import { Theme } from '@mui/material/styles';
4
+ import * as React$1 from 'react';
5
5
  import { PaperProps } from '@mui/material/Paper';
6
6
  import { SnackbarProps } from '@mui/material/Snackbar';
7
7
  import { FabProps } from '@mui/material/Fab';
@@ -653,18 +653,23 @@ interface ConsentProviderProps {
653
653
  */
654
654
  texts?: Partial<ConsentTexts>;
655
655
  /**
656
- * Tema customizado Material-UI aplicado aos componentes.
657
- * Aceita qualquer objeto que será passado para ThemeProvider.
656
+ * Tema Material-UI a ser aplicado aos componentes via ThemeProvider.
657
+ *
658
+ * Observação importante: a biblioteca NÃO cria/mescla tema automaticamente.
659
+ * Se você fornecer um `theme` aqui, ele será repassado diretamente ao `ThemeProvider`.
660
+ * Se não fornecer, a lib não envolverá com `ThemeProvider` e herdará o tema do app.
658
661
  *
659
662
  * @example
660
663
  * ```tsx
661
- * theme={{
662
- * palette: { primary: { main: '#1976d2' } },
663
- * components: { MuiButton: { styleOverrides: { root: { borderRadius: 8 } } } }
664
- * }}
664
+ * import { createTheme } from '@mui/material/styles'
665
+ * const appTheme = createTheme({ palette: { primary: { main: '#1976d2' } } })
666
+ *
667
+ * <ConsentProvider theme={appTheme}>
668
+ * <App />
669
+ * </ConsentProvider>
665
670
  * ```
666
671
  */
667
- theme?: any;
672
+ theme?: Theme;
668
673
  /**
669
674
  * Tokens de design para customização visual avançada.
670
675
  * Oferece controle direto sobre cores, fontes, espaçamento e layout.
@@ -684,24 +689,24 @@ interface ConsentProviderProps {
684
689
  * Deve implementar a lógica de consentimento usando as props definidas em `CustomPreferencesModalProps`.
685
690
  */
686
691
  PreferencesModalComponent?: React.ComponentType<CustomPreferencesModalProps>;
687
- /** Props adicionais passadas para o modal customizado. */
688
- preferencesModalProps?: Record<string, any>;
692
+ /** Props adicionais passadas para o modal customizado (repassadas sem transformação). */
693
+ preferencesModalProps?: Record<string, unknown>;
689
694
  /**
690
695
  * Componente customizado para substituir o banner padrão de cookies.
691
696
  * Se não fornecido, o `CookieBanner` padrão será renderizado.
692
697
  * Deve implementar a lógica de consentimento usando as props definidas em `CustomCookieBannerProps`.
693
698
  */
694
699
  CookieBannerComponent?: React.ComponentType<CustomCookieBannerProps>;
695
- /** Props adicionais passadas para o banner customizado. */
696
- cookieBannerProps?: Record<string, any>;
700
+ /** Props adicionais passadas para o banner customizado (repassadas sem transformação). */
701
+ cookieBannerProps?: Record<string, unknown>;
697
702
  /**
698
703
  * Componente customizado para substituir o botão flutuante de preferências.
699
704
  * Se não fornecido, o `FloatingPreferencesButton` padrão será renderizado.
700
705
  * Deve implementar a lógica de consentimento usando as props definidas em `CustomFloatingPreferencesButtonProps`.
701
706
  */
702
707
  FloatingPreferencesButtonComponent?: React.ComponentType<CustomFloatingPreferencesButtonProps>;
703
- /** Props adicionais passadas para o botão flutuante customizado. */
704
- floatingPreferencesButtonProps?: Record<string, any>;
708
+ /** Props adicionais passadas para o botão flutuante customizado (repassadas sem transformação). */
709
+ floatingPreferencesButtonProps?: Record<string, unknown>;
705
710
  /**
706
711
  * Desabilita o botão flutuante de preferências.
707
712
  * Útil quando o usuário da lib quer ter controle total sobre o acesso às preferências.
@@ -1600,7 +1605,7 @@ declare function ConsentGate(props: Readonly<{
1600
1605
  *
1601
1606
  * @param {string} id Um identificador único para o elemento `<script>` a ser criado.
1602
1607
  * @param {string} src A URL do script externo a ser carregado.
1603
- * @param {'analytics' | 'marketing' | null} [category=null] A categoria de consentimento exigida para o script. Se o consentimento para esta categoria não for dado, o script não será carregado.
1608
+ * @param {import('../types/types').Category | null} [category=null] A categoria de consentimento exigida para o script. Se o consentimento para esta categoria não for dado, o script não será carregado.
1604
1609
  * @param {Record<string, string>} [attrs={}] Atributos adicionais a serem aplicados ao elemento `<script>` (ex: `{ async: 'true' }`).
1605
1610
  * @returns {Promise<void>} Uma Promise que resolve quando o script é carregado com sucesso, ou rejeita se o consentimento não for dado ou ocorrer um erro de carregamento.
1606
1611
  * @example
@@ -1611,7 +1616,8 @@ declare function ConsentGate(props: Readonly<{
1611
1616
  * .catch(error => console.error('Erro ao carregar script:', error))
1612
1617
  * ```
1613
1618
  */
1614
- declare function loadScript(id: string, src: string, category?: 'analytics' | 'marketing' | null, attrs?: Record<string, string>): Promise<void>;
1619
+
1620
+ declare function loadScript(id: string, src: string, category?: Category | null, attrs?: Record<string, string>): Promise<void>;
1615
1621
 
1616
1622
  /**
1617
1623
  * @constant
@@ -1637,13 +1643,19 @@ declare const defaultConsentTheme: () => Theme;
1637
1643
 
1638
1644
  /**
1639
1645
  * @interface ScriptIntegration
1640
- * Define a estrutura de um objeto de integração de script, usado para carregar scripts de terceiros condicionalmente.
1646
+ * Estrutura de uma integração de script de terceiros a ser carregada condicionalmente conforme o consentimento.
1647
+ *
1648
+ * @remarks
1649
+ * - `category` é um `Category` tipado (ex.: 'analytics', 'marketing').
1650
+ * - `init` roda após o script ser inserido no DOM e carregado.
1651
+ * - `attrs` é repassado como atributos HTML da tag `<script>`.
1641
1652
  */
1653
+
1642
1654
  interface ScriptIntegration {
1643
1655
  /** Um ID único para esta integração de script. */
1644
1656
  id: string;
1645
- /** A categoria de consentimento necessária para que este script seja carregado (ex: 'analytics', 'marketing'). */
1646
- category: string;
1657
+ /** Categoria de consentimento necessária para carregar o script. */
1658
+ category: Category;
1647
1659
  /** A URL do script a ser carregado. */
1648
1660
  src: string;
1649
1661
  /** Uma função opcional a ser executada após o script ser carregado e inicializado no DOM. */
@@ -1658,8 +1670,8 @@ interface ScriptIntegration {
1658
1670
  interface GoogleAnalyticsConfig {
1659
1671
  /** O ID de medição do GA4 (ex: 'G-XXXXXXXXXX'). */
1660
1672
  measurementId: string;
1661
- /** Um objeto opcional de configuração adicional a ser passado para o comando `gtag('config')`. */
1662
- config?: any;
1673
+ /** Objeto opcional repassado para `gtag('config')`. */
1674
+ config?: Record<string, unknown>;
1663
1675
  }
1664
1676
  /**
1665
1677
  * @interface GoogleTagManagerConfig
@@ -1683,30 +1695,30 @@ interface UserWayConfig {
1683
1695
  * @function
1684
1696
  * @category Utils
1685
1697
  * @since 0.2.0
1686
- * Cria um objeto de integração para o Google Analytics 4 (GA4).
1698
+ * Cria uma integração para Google Analytics 4 (GA4).
1687
1699
  *
1688
- * @param {GoogleAnalyticsConfig} config A configuração do GA4, incluindo o `measurementId`.
1689
- * @returns {ScriptIntegration} Um objeto `ScriptIntegration` configurado para o GA4.
1700
+ * @param {GoogleAnalyticsConfig} config Configuração com `measurementId` e `config` opcional.
1701
+ * @returns {ScriptIntegration} Integração tipada com `category: 'analytics'`.
1690
1702
  */
1691
1703
  declare function createGoogleAnalyticsIntegration(config: GoogleAnalyticsConfig): ScriptIntegration;
1692
1704
  /**
1693
1705
  * @function
1694
1706
  * @category Utils
1695
1707
  * @since 0.2.0
1696
- * Cria um objeto de integração para o Google Tag Manager (GTM).
1708
+ * Cria uma integração para Google Tag Manager (GTM).
1697
1709
  *
1698
- * @param {GoogleTagManagerConfig} config A configuração do GTM, incluindo o `containerId`.
1699
- * @returns {ScriptIntegration} Um objeto `ScriptIntegration` configurado para o GTM.
1710
+ * @param {GoogleTagManagerConfig} config Configuração com `containerId` e `dataLayerName` opcional.
1711
+ * @returns {ScriptIntegration} Integração tipada com `category: 'analytics'`.
1700
1712
  */
1701
1713
  declare function createGoogleTagManagerIntegration(config: GoogleTagManagerConfig): ScriptIntegration;
1702
1714
  /**
1703
1715
  * @function
1704
1716
  * @category Utils
1705
1717
  * @since 0.2.0
1706
- * Cria um objeto de integração para o widget de acessibilidade UserWay.
1718
+ * Cria uma integração para o widget de acessibilidade UserWay.
1707
1719
  *
1708
- * @param {UserWayConfig} config A configuração do UserWay, incluindo o `accountId`.
1709
- * @returns {ScriptIntegration} Um objeto `ScriptIntegration` configurado para o UserWay.
1720
+ * @param {UserWayConfig} config Configuração com `accountId`.
1721
+ * @returns {ScriptIntegration} Integração tipada com `category: 'functional'`.
1710
1722
  */
1711
1723
  declare function createUserWayIntegration(config: UserWayConfig): ScriptIntegration;
1712
1724
  /**
package/dist/index.js CHANGED
@@ -19,7 +19,7 @@ import {
19
19
  useConsentTexts,
20
20
  useOpenPreferencesModal,
21
21
  validateProjectPreferences
22
- } from "./chunk-MHCQFGRJ.js";
22
+ } from "./chunk-TKN3PNIW.js";
23
23
 
24
24
  // src/utils/ConsentGate.tsx
25
25
  import { Fragment, jsx } from "react/jsx-runtime";
@@ -152,13 +152,7 @@ function ConsentScriptLoader({
152
152
  const alreadyLoaded = loadedScripts.current.has(integration.id);
153
153
  if (shouldLoad && (!alreadyLoaded || reloadOnChange)) {
154
154
  try {
155
- await loadScript(
156
- integration.id,
157
- integration.src,
158
- integration.category,
159
- // Categoria dinâmica
160
- integration.attrs
161
- );
155
+ await loadScript(integration.id, integration.src, integration.category, integration.attrs);
162
156
  if (integration.init) {
163
157
  integration.init();
164
158
  }
@@ -187,13 +181,7 @@ function useConsentScriptLoader() {
187
181
  return false;
188
182
  }
189
183
  try {
190
- await loadScript(
191
- integration.id,
192
- integration.src,
193
- integration.category,
194
- // Categoria dinâmica
195
- integration.attrs
196
- );
184
+ await loadScript(integration.id, integration.src, integration.category, integration.attrs);
197
185
  if (integration.init) {
198
186
  integration.init();
199
187
  }
@@ -215,14 +203,14 @@ function createGoogleAnalyticsIntegration(config) {
215
203
  src: `https://www.googletagmanager.com/gtag/js?id=${config.measurementId}`,
216
204
  init: () => {
217
205
  if (typeof window !== "undefined") {
218
- let gtag2 = function(...args) {
219
- window.dataLayer.push(...args);
206
+ const w = window;
207
+ w.dataLayer = w.dataLayer ?? [];
208
+ const gtag = (...args) => {
209
+ w.dataLayer.push(...args);
220
210
  };
221
- var gtag = gtag2;
222
- window.dataLayer = window.dataLayer || [];
223
- window.gtag = gtag2;
224
- gtag2("js", /* @__PURE__ */ new Date());
225
- gtag2("config", config.measurementId, config.config || {});
211
+ w.gtag = gtag;
212
+ gtag("js", /* @__PURE__ */ new Date());
213
+ gtag("config", config.measurementId, config.config ?? {});
226
214
  }
227
215
  },
228
216
  attrs: { async: "true" }
@@ -236,8 +224,10 @@ function createGoogleTagManagerIntegration(config) {
236
224
  init: () => {
237
225
  if (typeof window !== "undefined") {
238
226
  const dataLayerName = config.dataLayerName || "dataLayer";
239
- window[dataLayerName] = window[dataLayerName] || [];
240
- window[dataLayerName].push({
227
+ const w = window;
228
+ const layer = w[dataLayerName] ?? [];
229
+ w[dataLayerName] = layer;
230
+ layer.push({
241
231
  "gtm.start": (/* @__PURE__ */ new Date()).getTime(),
242
232
  event: "gtm.js"
243
233
  });
@@ -252,8 +242,9 @@ function createUserWayIntegration(config) {
252
242
  src: "https://cdn.userway.org/widget.js",
253
243
  init: () => {
254
244
  if (typeof window !== "undefined") {
255
- window.UserWayWidgetApp = window.UserWayWidgetApp || {};
256
- window.UserWayWidgetApp.accountId = config.accountId;
245
+ const w = window;
246
+ w.UserWayWidgetApp = w.UserWayWidgetApp || {};
247
+ w.UserWayWidgetApp.accountId = config.accountId;
257
248
  }
258
249
  },
259
250
  attrs: { "data-account": config.accountId }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-lgpd-consent",
3
- "version": "0.3.5",
3
+ "version": "0.3.7",
4
4
  "description": "Biblioteca de consentimento LGPD, integrações nativas e sistema extensível para React.",
5
5
  "keywords": [
6
6
  "lgpd",
@@ -54,14 +54,15 @@
54
54
  "CHANGELOG.md"
55
55
  ],
56
56
  "engines": {
57
- "node": ">=18.18"
57
+ "node": ">=20.0.0"
58
58
  },
59
- "packageManager": "npm@10.9.3",
59
+ "packageManager": "npm@11.6.0",
60
60
  "scripts": {
61
61
  "clean": "rimraf node_modules package-lock.json dist docs storybook-static .cache .stryker-tmp",
62
62
  "build": "cross-env NODE_ENV=production tsup src/index.ts --format esm,cjs --dts --clean",
63
63
  "dev": "cross-env NODE_ENV=development tsup src/index.ts --format esm,cjs --dts --watch",
64
- "lint": "eslint . --ext .ts,.tsx",
64
+ "lint": "eslint \"**/*.{ts,tsx}\" --cache",
65
+ "lint:ci": "eslint \"**/*.{ts,tsx}\" --cache --max-warnings=0",
65
66
  "format": "prettier --write \"src/**/*.{ts,tsx,json,md}\" \"eslint.config.js\"",
66
67
  "type-check": "tsc --noEmit",
67
68
  "test": "jest --config jest.config.ts",
@@ -95,47 +96,48 @@
95
96
  "js-cookie": "^3.0.5"
96
97
  },
97
98
  "devDependencies": {
98
- "@chromatic-com/storybook": "^4.1.1",
99
- "@emotion/react": "^11.14.0",
100
- "@emotion/styled": "^11.14.1",
101
- "@eslint/compat": "^1.3.2",
102
- "@mui/icons-material": "^7.3.1",
103
- "@mui/material": "^7.3.1",
104
- "@storybook/addon-a11y": "^9.1.3",
105
- "@storybook/addon-docs": "^9.1.3",
106
- "@storybook/addon-vitest": "^9.1.3",
107
- "@storybook/react-vite": "^9.1.3",
108
- "@stryker-mutator/core": "^9.0.1",
109
- "@stryker-mutator/jest-runner": "^9.0.1",
110
- "@testing-library/dom": "^10.4.1",
111
- "@testing-library/jest-dom": "^6.8.0",
112
- "@testing-library/react": "^16.3.0",
113
- "@testing-library/user-event": "^14.6.1",
114
- "@types/jest": "^30.0.0",
115
- "@types/js-cookie": "^3.0.6",
116
- "@types/node": "^24.3.0",
117
- "@types/react": "^19.1.12",
118
- "@types/react-dom": "^19.1.9",
119
- "@typescript-eslint/eslint-plugin": "^8.41.0",
120
- "@typescript-eslint/parser": "^8.41.0",
121
- "cross-env": "^10.0.0",
122
- "eslint": "^9.34.0",
123
- "eslint-config-prettier": "^10.1.8",
124
- "eslint-plugin-jest": "^29.0.1",
125
- "eslint-plugin-react-hooks": "^5.2.0",
126
- "eslint-plugin-storybook": "^9.1.3",
127
- "jest": "^30.1.1",
128
- "jest-environment-jsdom": "^30.1.1",
129
- "prettier": "^3.6.2",
130
- "react": "^19.1.1",
131
- "react-dom": "^19.1.1",
132
- "rimraf": "^6.0.1",
133
- "storybook": "^9.1.3",
134
- "ts-jest": "^29.4.1",
135
- "ts-node": "^10.9.2",
136
- "tsup": "^8.5.0",
137
- "typedoc": "^0.28.11",
138
- "typescript": "^5.9.2",
139
- "typescript-eslint": "^8.41.0"
99
+ "@chromatic-com/storybook": "4.1.1",
100
+ "@emotion/react": "11.14.0",
101
+ "@emotion/styled": "11.14.1",
102
+ "@eslint/compat": "1.3.2",
103
+ "@mui/icons-material": "7.3.2",
104
+ "@mui/material": "7.3.2",
105
+ "@storybook/addon-a11y": "9.1.5",
106
+ "@storybook/addon-docs": "9.1.5",
107
+ "@storybook/addon-vitest": "9.1.5",
108
+ "@storybook/react-vite": "9.1.5",
109
+ "@stryker-mutator/core": "9.1.1",
110
+ "@stryker-mutator/jest-runner": "9.1.1",
111
+ "@testing-library/dom": "10.4.1",
112
+ "@testing-library/jest-dom": "6.8.0",
113
+ "@testing-library/react": "16.3.0",
114
+ "@testing-library/user-event": "14.6.1",
115
+ "@types/jest": "29.5.12",
116
+ "@types/js-cookie": "3.0.6",
117
+ "@types/node": "24.3.1",
118
+ "@types/react": "19.1.12",
119
+ "@types/react-dom": "19.1.9",
120
+ "@typescript-eslint/eslint-plugin": "8.43.0",
121
+ "@typescript-eslint/parser": "8.43.0",
122
+ "cross-env": "10.0.0",
123
+ "eslint": "8.57.0",
124
+ "eslint-config-prettier": "10.1.8",
125
+ "eslint-plugin-jest": "29.0.1",
126
+ "eslint-plugin-react-hooks": "5.2.0",
127
+ "eslint-plugin-storybook": "9.1.5",
128
+ "globals": "^15.15.0",
129
+ "jest": "29.7.0",
130
+ "jest-environment-jsdom": "29.7.0",
131
+ "prettier": "3.6.2",
132
+ "react": "19.1.1",
133
+ "react-dom": "19.1.1",
134
+ "rimraf": "6.0.1",
135
+ "storybook": "9.1.5",
136
+ "ts-jest": "29.4.1",
137
+ "ts-node": "10.9.2",
138
+ "tsup": "8.5.0",
139
+ "typedoc": "0.28.12",
140
+ "typescript": "5.9.2",
141
+ "typescript-eslint": "8.43.0"
140
142
  }
141
143
  }