react-lgpd-consent 0.3.6 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -86,6 +86,17 @@ function analyzeDeveloperConfiguration(config) {
86
86
  });
87
87
  }
88
88
  });
89
+ const custom = finalConfig.customCategories || [];
90
+ custom.forEach((cat) => {
91
+ if (!cat?.id || cat.id === "necessary") return;
92
+ guidance.activeCategoriesInfo.push({
93
+ id: cat.id,
94
+ name: cat.name,
95
+ description: cat.description,
96
+ essential: !!cat.essential,
97
+ uiRequired: !cat.essential
98
+ });
99
+ });
89
100
  const totalToggleable = guidance.activeCategoriesInfo.filter((c) => c.uiRequired).length;
90
101
  if (totalToggleable === 0) {
91
102
  guidance.suggestions.push(
@@ -100,9 +111,10 @@ function analyzeDeveloperConfiguration(config) {
100
111
  return guidance;
101
112
  }
102
113
  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";
114
+ const gt = globalThis;
115
+ const nodeEnv = typeof gt.process !== "undefined" ? gt.process?.env?.NODE_ENV : void 0;
116
+ const isProd = nodeEnv === "production" || gt.__LGPD_PRODUCTION__ === true;
117
+ const isDisabled = !!disableGuidanceProp || gt.__LGPD_DISABLE_GUIDANCE__ === true;
106
118
  if (isProd || isDisabled) return;
107
119
  const PREFIX = "[\u{1F36A} LGPD-CONSENT]";
108
120
  if (guidance.warnings.length > 0) {
@@ -250,7 +262,7 @@ var init_logger = __esm({
250
262
  }
251
263
  /**
252
264
  * Registra uma mensagem de erro.
253
- * @param {...any[]} args Os argumentos a serem logados.
265
+ * @param {...unknown[]} args Argumentos a serem logados.
254
266
  */
255
267
  error(...args) {
256
268
  if (this.enabled && this.level >= 0 /* ERROR */) {
@@ -259,7 +271,7 @@ var init_logger = __esm({
259
271
  }
260
272
  /**
261
273
  * Registra uma mensagem de aviso.
262
- * @param {...any[]} args Os argumentos a serem logados.
274
+ * @param {...unknown[]} args Argumentos a serem logados.
263
275
  */
264
276
  warn(...args) {
265
277
  if (this.enabled && this.level >= 1 /* WARN */) {
@@ -268,7 +280,7 @@ var init_logger = __esm({
268
280
  }
269
281
  /**
270
282
  * Registra uma mensagem informativa.
271
- * @param {...any[]} args Os argumentos a serem logados.
283
+ * @param {...unknown[]} args Argumentos a serem logados.
272
284
  */
273
285
  info(...args) {
274
286
  if (this.enabled && this.level >= 2 /* INFO */) {
@@ -277,7 +289,7 @@ var init_logger = __esm({
277
289
  }
278
290
  /**
279
291
  * Registra uma mensagem de depuração.
280
- * @param {...any[]} args Os argumentos a serem logados.
292
+ * @param {...unknown[]} args Argumentos a serem logados.
281
293
  */
282
294
  debug(...args) {
283
295
  if (this.enabled && this.level >= 3 /* DEBUG */) {
@@ -286,7 +298,7 @@ var init_logger = __esm({
286
298
  }
287
299
  /**
288
300
  * Inicia um grupo de logs no console.
289
- * @param {...any[]} args Os argumentos para o título do grupo.
301
+ * @param {...unknown[]} args Argumentos para o título do grupo.
290
302
  */
291
303
  group(...args) {
292
304
  if (this.enabled && this.level >= 3 /* DEBUG */) {
@@ -303,8 +315,8 @@ var init_logger = __esm({
303
315
  }
304
316
  /**
305
317
  * 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.
318
+ * @param {unknown} tabularData Dados a serem exibidos na tabela.
319
+ * @param {string[]} [properties] Propriedades opcionais para exibir.
308
320
  */
309
321
  table(tabularData, properties) {
310
322
  if (this.enabled && this.level >= 3 /* DEBUG */) {
@@ -313,21 +325,27 @@ var init_logger = __esm({
313
325
  }
314
326
  /**
315
327
  * Registra informações sobre a compatibilidade do tema Material-UI.
316
- * @param {any} themeInfo Objeto com informações do tema.
328
+ * @param {unknown} themeInfo Objeto potencialmente parcial do tema (inspeção segura).
317
329
  */
318
330
  themeCompatibility(themeInfo) {
331
+ const isRecord = (v) => typeof v === "object" && v !== null;
332
+ const theme = isRecord(themeInfo) ? themeInfo : void 0;
333
+ const palette = theme && isRecord(theme["palette"]) ? theme["palette"] : void 0;
334
+ const primary = palette && isRecord(palette["primary"]);
335
+ const transitions = theme && isRecord(theme["transitions"]) ? theme["transitions"] : void 0;
336
+ const duration = transitions && isRecord(transitions["duration"]);
319
337
  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
338
+ hasTheme: !!theme,
339
+ hasPalette: !!palette,
340
+ hasPrimary: !!primary,
341
+ hasTransitions: !!transitions,
342
+ hasDuration: !!duration
325
343
  });
326
344
  }
327
345
  /**
328
346
  * 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.
347
+ * @param {string} action Ação que causou a mudança de estado.
348
+ * @param {{ consented?: boolean; isModalOpen?: boolean; preferences?: Record<string, unknown> }} state Estado atual.
331
349
  */
332
350
  consentState(action, state) {
333
351
  this.debug(`Consent state change [${action}]:`, {
@@ -338,9 +356,9 @@ var init_logger = __esm({
338
356
  }
339
357
  /**
340
358
  * 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.
359
+ * @param {'read' | 'write' | 'delete'} operation Tipo de operação.
360
+ * @param {string} cookieName Nome do cookie.
361
+ * @param {unknown} [data] Dados associados, se aplicável.
344
362
  */
345
363
  cookieOperation(operation, cookieName, data) {
346
364
  this.debug(`Cookie ${operation}:`, {
@@ -351,8 +369,8 @@ var init_logger = __esm({
351
369
  }
352
370
  /**
353
371
  * Registra a renderização de um componente.
354
- * @param {string} componentName O nome do componente.
355
- * @param {any} [props] As propriedades do componente.
372
+ * @param {string} componentName Nome do componente.
373
+ * @param {Record<string, unknown>} [props] Propriedades do componente.
356
374
  */
357
375
  componentRender(componentName, props) {
358
376
  this.debug(`Component render [${componentName}]:`, {
@@ -371,8 +389,8 @@ var init_logger = __esm({
371
389
  }
372
390
  /**
373
391
  * 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.
392
+ * @param {string} method Nome do método da API chamado.
393
+ * @param {unknown} [params] Parâmetros passados para o método.
376
394
  */
377
395
  apiUsage(method, params) {
378
396
  this.debug(`API call [${method}]:`, params);
@@ -419,8 +437,8 @@ function migrateLegacyCookie(legacyData) {
419
437
  const now = (/* @__PURE__ */ new Date()).toISOString();
420
438
  return {
421
439
  version: COOKIE_SCHEMA_VERSION,
422
- consented: legacyData.consented || false,
423
- preferences: legacyData.preferences || { necessary: true },
440
+ consented: Boolean(legacyData.consented) || false,
441
+ preferences: legacyData.preferences && typeof legacyData.preferences === "object" ? legacyData.preferences : { necessary: true },
424
442
  consentDate: now,
425
443
  lastUpdate: now,
426
444
  source: "banner",
@@ -498,6 +516,12 @@ function createProjectPreferences(config, defaultValue = false) {
498
516
  preferences[category] = defaultValue;
499
517
  }
500
518
  });
519
+ const custom = config?.customCategories || [];
520
+ custom.forEach((cat) => {
521
+ if (cat.id && cat.id !== "necessary") {
522
+ preferences[cat.id] = defaultValue;
523
+ }
524
+ });
501
525
  return preferences;
502
526
  }
503
527
  function validateProjectPreferences(preferences, config) {
@@ -511,6 +535,13 @@ function validateProjectPreferences(preferences, config) {
511
535
  validPreferences[category] = preferences[category];
512
536
  }
513
537
  });
538
+ const custom = config?.customCategories || [];
539
+ custom.forEach((cat) => {
540
+ const id = cat.id;
541
+ if (id && id !== "necessary" && preferences[id] !== void 0) {
542
+ validPreferences[id] = preferences[id];
543
+ }
544
+ });
514
545
  return validPreferences;
515
546
  }
516
547
  function getAllProjectCategories(config) {
@@ -528,6 +559,12 @@ function getAllProjectCategories(config) {
528
559
  allCategories.push(getDefaultCategoryDefinition(category));
529
560
  }
530
561
  });
562
+ const custom = config?.customCategories || [];
563
+ custom.forEach((cat) => {
564
+ if (cat.id && cat.id !== "necessary") {
565
+ allCategories.push({ ...cat, essential: !!cat.essential });
566
+ }
567
+ });
531
568
  return allCategories;
532
569
  }
533
570
  function getDefaultCategoryDefinition(category) {
@@ -1169,12 +1206,17 @@ function ConsentProvider({
1169
1206
  }
1170
1207
  ) : (
1171
1208
  // Encaminha `floatingPreferencesButtonProps` para o componente padrão
1172
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(FloatingPreferencesButton, { ...floatingPreferencesButtonProps })
1209
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1210
+ FloatingPreferencesButton,
1211
+ {
1212
+ ...floatingPreferencesButtonProps ?? {}
1213
+ }
1214
+ )
1173
1215
  ))
1174
1216
  ]
1175
1217
  }
1176
1218
  ) }) }) }) }) });
1177
- if (theme) {
1219
+ if (mergedTheme) {
1178
1220
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_styles2.ThemeProvider, { theme: mergedTheme, children: content });
1179
1221
  }
1180
1222
  return content;
@@ -1592,13 +1634,7 @@ function ConsentScriptLoader({
1592
1634
  const alreadyLoaded = loadedScripts.current.has(integration.id);
1593
1635
  if (shouldLoad && (!alreadyLoaded || reloadOnChange)) {
1594
1636
  try {
1595
- await loadScript(
1596
- integration.id,
1597
- integration.src,
1598
- integration.category,
1599
- // Categoria dinâmica
1600
- integration.attrs
1601
- );
1637
+ await loadScript(integration.id, integration.src, integration.category, integration.attrs);
1602
1638
  if (integration.init) {
1603
1639
  integration.init();
1604
1640
  }
@@ -1627,13 +1663,7 @@ function useConsentScriptLoader() {
1627
1663
  return false;
1628
1664
  }
1629
1665
  try {
1630
- await loadScript(
1631
- integration.id,
1632
- integration.src,
1633
- integration.category,
1634
- // Categoria dinâmica
1635
- integration.attrs
1636
- );
1666
+ await loadScript(integration.id, integration.src, integration.category, integration.attrs);
1637
1667
  if (integration.init) {
1638
1668
  integration.init();
1639
1669
  }
@@ -1655,14 +1685,14 @@ function createGoogleAnalyticsIntegration(config) {
1655
1685
  src: `https://www.googletagmanager.com/gtag/js?id=${config.measurementId}`,
1656
1686
  init: () => {
1657
1687
  if (typeof window !== "undefined") {
1658
- let gtag2 = function(...args) {
1659
- window.dataLayer.push(...args);
1688
+ const w = window;
1689
+ w.dataLayer = w.dataLayer ?? [];
1690
+ const gtag = (...args) => {
1691
+ w.dataLayer.push(...args);
1660
1692
  };
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 || {});
1693
+ w.gtag = gtag;
1694
+ gtag("js", /* @__PURE__ */ new Date());
1695
+ gtag("config", config.measurementId, config.config ?? {});
1666
1696
  }
1667
1697
  },
1668
1698
  attrs: { async: "true" }
@@ -1676,8 +1706,10 @@ function createGoogleTagManagerIntegration(config) {
1676
1706
  init: () => {
1677
1707
  if (typeof window !== "undefined") {
1678
1708
  const dataLayerName = config.dataLayerName || "dataLayer";
1679
- window[dataLayerName] = window[dataLayerName] || [];
1680
- window[dataLayerName].push({
1709
+ const w = window;
1710
+ const layer = w[dataLayerName] ?? [];
1711
+ w[dataLayerName] = layer;
1712
+ layer.push({
1681
1713
  "gtm.start": (/* @__PURE__ */ new Date()).getTime(),
1682
1714
  event: "gtm.js"
1683
1715
  });
@@ -1692,8 +1724,9 @@ function createUserWayIntegration(config) {
1692
1724
  src: "https://cdn.userway.org/widget.js",
1693
1725
  init: () => {
1694
1726
  if (typeof window !== "undefined") {
1695
- window.UserWayWidgetApp = window.UserWayWidgetApp || {};
1696
- window.UserWayWidgetApp.accountId = config.accountId;
1727
+ const w = window;
1728
+ w.UserWayWidgetApp = w.UserWayWidgetApp || {};
1729
+ w.UserWayWidgetApp.accountId = config.accountId;
1697
1730
  }
1698
1731
  },
1699
1732
  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';
@@ -81,6 +81,7 @@ type Category = 'necessary' | 'analytics' | 'functional' | 'marketing' | 'social
81
81
  *
82
82
  * @example
83
83
  * ```typescript
84
+ * // Categoria padrão da biblioteca
84
85
  * const analyticsCategory: CategoryDefinition = {
85
86
  * id: 'analytics',
86
87
  * name: 'Cookies Analíticos',
@@ -88,6 +89,14 @@ type Category = 'necessary' | 'analytics' | 'functional' | 'marketing' | 'social
88
89
  * essential: false,
89
90
  * cookies: ['_ga', '_ga_*', '_gid']
90
91
  * };
92
+ *
93
+ * // Categoria customizada específica do projeto
94
+ * const chatCategory: CategoryDefinition = {
95
+ * id: 'chat',
96
+ * name: 'Chat de Suporte',
97
+ * description: 'Widget de chat para suporte ao cliente',
98
+ * essential: false
99
+ * };
91
100
  * ```
92
101
  *
93
102
  * @public
@@ -144,11 +153,18 @@ interface CategoryDefinition {
144
153
  * // Configuração com categorias customizadas
145
154
  * const config: ProjectCategoriesConfig = {
146
155
  * enabledCategories: ['analytics'],
147
- * customCategories: [{
148
- * id: 'support',
149
- * name: 'Suporte',
150
- * description: 'Cookies para sistema de suporte ao cliente'
151
- * }]
156
+ * customCategories: [
157
+ * {
158
+ * id: 'chat',
159
+ * name: 'Chat de Suporte',
160
+ * description: 'Widget de chat para suporte ao cliente'
161
+ * },
162
+ * {
163
+ * id: 'abTesting',
164
+ * name: 'A/B Testing',
165
+ * description: 'Experimentos de interface e funcionalidades'
166
+ * }
167
+ * ]
152
168
  * };
153
169
  * ```
154
170
  *
@@ -164,6 +180,7 @@ interface ProjectCategoriesConfig {
164
180
  /**
165
181
  * Categorias customizadas específicas do projeto.
166
182
  * Permite extensão além das categorias padrão da biblioteca.
183
+ * @example [{ id: 'chat', name: 'Chat de Suporte', description: 'Widget de chat' }]
167
184
  */
168
185
  customCategories?: CategoryDefinition[];
169
186
  }
@@ -653,18 +670,23 @@ interface ConsentProviderProps {
653
670
  */
654
671
  texts?: Partial<ConsentTexts>;
655
672
  /**
656
- * Tema customizado Material-UI aplicado aos componentes.
657
- * Aceita qualquer objeto que será passado para ThemeProvider.
673
+ * Tema Material-UI a ser aplicado aos componentes via ThemeProvider.
674
+ *
675
+ * Observação importante: a biblioteca NÃO cria/mescla tema automaticamente.
676
+ * Se você fornecer um `theme` aqui, ele será repassado diretamente ao `ThemeProvider`.
677
+ * Se não fornecer, a lib não envolverá com `ThemeProvider` e herdará o tema do app.
658
678
  *
659
679
  * @example
660
680
  * ```tsx
661
- * theme={{
662
- * palette: { primary: { main: '#1976d2' } },
663
- * components: { MuiButton: { styleOverrides: { root: { borderRadius: 8 } } } }
664
- * }}
681
+ * import { createTheme } from '@mui/material/styles'
682
+ * const appTheme = createTheme({ palette: { primary: { main: '#1976d2' } } })
683
+ *
684
+ * <ConsentProvider theme={appTheme}>
685
+ * <App />
686
+ * </ConsentProvider>
665
687
  * ```
666
688
  */
667
- theme?: any;
689
+ theme?: Theme;
668
690
  /**
669
691
  * Tokens de design para customização visual avançada.
670
692
  * Oferece controle direto sobre cores, fontes, espaçamento e layout.
@@ -684,24 +706,24 @@ interface ConsentProviderProps {
684
706
  * Deve implementar a lógica de consentimento usando as props definidas em `CustomPreferencesModalProps`.
685
707
  */
686
708
  PreferencesModalComponent?: React.ComponentType<CustomPreferencesModalProps>;
687
- /** Props adicionais passadas para o modal customizado. */
688
- preferencesModalProps?: Record<string, any>;
709
+ /** Props adicionais passadas para o modal customizado (repassadas sem transformação). */
710
+ preferencesModalProps?: Record<string, unknown>;
689
711
  /**
690
712
  * Componente customizado para substituir o banner padrão de cookies.
691
713
  * Se não fornecido, o `CookieBanner` padrão será renderizado.
692
714
  * Deve implementar a lógica de consentimento usando as props definidas em `CustomCookieBannerProps`.
693
715
  */
694
716
  CookieBannerComponent?: React.ComponentType<CustomCookieBannerProps>;
695
- /** Props adicionais passadas para o banner customizado. */
696
- cookieBannerProps?: Record<string, any>;
717
+ /** Props adicionais passadas para o banner customizado (repassadas sem transformação). */
718
+ cookieBannerProps?: Record<string, unknown>;
697
719
  /**
698
720
  * Componente customizado para substituir o botão flutuante de preferências.
699
721
  * Se não fornecido, o `FloatingPreferencesButton` padrão será renderizado.
700
722
  * Deve implementar a lógica de consentimento usando as props definidas em `CustomFloatingPreferencesButtonProps`.
701
723
  */
702
724
  FloatingPreferencesButtonComponent?: React.ComponentType<CustomFloatingPreferencesButtonProps>;
703
- /** Props adicionais passadas para o botão flutuante customizado. */
704
- floatingPreferencesButtonProps?: Record<string, any>;
725
+ /** Props adicionais passadas para o botão flutuante customizado (repassadas sem transformação). */
726
+ floatingPreferencesButtonProps?: Record<string, unknown>;
705
727
  /**
706
728
  * Desabilita o botão flutuante de preferências.
707
729
  * Útil quando o usuário da lib quer ter controle total sobre o acesso às preferências.
@@ -1521,6 +1543,8 @@ declare const DEFAULT_PROJECT_CATEGORIES: ProjectCategoriesConfig;
1521
1543
  *
1522
1544
  * @param {ProjectCategoriesConfig} [config] A configuração de categorias fornecida pelo desenvolvedor. Se não for fornecida, a configuração padrão será utilizada.
1523
1545
  * @returns {DeveloperGuidance} Um objeto `DeveloperGuidance` com a análise da configuração.
1546
+ *
1547
+ * Since v0.4.0: inclui `customCategories` em `activeCategoriesInfo` (com `uiRequired=false` se `essential=true`).
1524
1548
  */
1525
1549
  declare function analyzeDeveloperConfiguration(config?: ProjectCategoriesConfig): DeveloperGuidance;
1526
1550
 
@@ -1600,7 +1624,7 @@ declare function ConsentGate(props: Readonly<{
1600
1624
  *
1601
1625
  * @param {string} id Um identificador único para o elemento `<script>` a ser criado.
1602
1626
  * @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.
1627
+ * @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
1628
  * @param {Record<string, string>} [attrs={}] Atributos adicionais a serem aplicados ao elemento `<script>` (ex: `{ async: 'true' }`).
1605
1629
  * @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
1630
  * @example
@@ -1611,7 +1635,8 @@ declare function ConsentGate(props: Readonly<{
1611
1635
  * .catch(error => console.error('Erro ao carregar script:', error))
1612
1636
  * ```
1613
1637
  */
1614
- declare function loadScript(id: string, src: string, category?: 'analytics' | 'marketing' | null, attrs?: Record<string, string>): Promise<void>;
1638
+
1639
+ declare function loadScript(id: string, src: string, category?: Category | null, attrs?: Record<string, string>): Promise<void>;
1615
1640
 
1616
1641
  /**
1617
1642
  * @constant
@@ -1637,13 +1662,19 @@ declare const defaultConsentTheme: () => Theme;
1637
1662
 
1638
1663
  /**
1639
1664
  * @interface ScriptIntegration
1640
- * Define a estrutura de um objeto de integração de script, usado para carregar scripts de terceiros condicionalmente.
1665
+ * Estrutura de uma integração de script de terceiros a ser carregada condicionalmente conforme o consentimento.
1666
+ *
1667
+ * @remarks
1668
+ * - `category` é um `Category` tipado (ex.: 'analytics', 'marketing').
1669
+ * - `init` roda após o script ser inserido no DOM e carregado.
1670
+ * - `attrs` é repassado como atributos HTML da tag `<script>`.
1641
1671
  */
1672
+
1642
1673
  interface ScriptIntegration {
1643
1674
  /** Um ID único para esta integração de script. */
1644
1675
  id: string;
1645
- /** A categoria de consentimento necessária para que este script seja carregado (ex: 'analytics', 'marketing'). */
1646
- category: string;
1676
+ /** Categoria de consentimento necessária para carregar o script. */
1677
+ category: Category;
1647
1678
  /** A URL do script a ser carregado. */
1648
1679
  src: string;
1649
1680
  /** Uma função opcional a ser executada após o script ser carregado e inicializado no DOM. */
@@ -1658,8 +1689,8 @@ interface ScriptIntegration {
1658
1689
  interface GoogleAnalyticsConfig {
1659
1690
  /** O ID de medição do GA4 (ex: 'G-XXXXXXXXXX'). */
1660
1691
  measurementId: string;
1661
- /** Um objeto opcional de configuração adicional a ser passado para o comando `gtag('config')`. */
1662
- config?: any;
1692
+ /** Objeto opcional repassado para `gtag('config')`. */
1693
+ config?: Record<string, unknown>;
1663
1694
  }
1664
1695
  /**
1665
1696
  * @interface GoogleTagManagerConfig
@@ -1683,30 +1714,30 @@ interface UserWayConfig {
1683
1714
  * @function
1684
1715
  * @category Utils
1685
1716
  * @since 0.2.0
1686
- * Cria um objeto de integração para o Google Analytics 4 (GA4).
1717
+ * Cria uma integração para Google Analytics 4 (GA4).
1687
1718
  *
1688
- * @param {GoogleAnalyticsConfig} config A configuração do GA4, incluindo o `measurementId`.
1689
- * @returns {ScriptIntegration} Um objeto `ScriptIntegration` configurado para o GA4.
1719
+ * @param {GoogleAnalyticsConfig} config Configuração com `measurementId` e `config` opcional.
1720
+ * @returns {ScriptIntegration} Integração tipada com `category: 'analytics'`.
1690
1721
  */
1691
1722
  declare function createGoogleAnalyticsIntegration(config: GoogleAnalyticsConfig): ScriptIntegration;
1692
1723
  /**
1693
1724
  * @function
1694
1725
  * @category Utils
1695
1726
  * @since 0.2.0
1696
- * Cria um objeto de integração para o Google Tag Manager (GTM).
1727
+ * Cria uma integração para Google Tag Manager (GTM).
1697
1728
  *
1698
- * @param {GoogleTagManagerConfig} config A configuração do GTM, incluindo o `containerId`.
1699
- * @returns {ScriptIntegration} Um objeto `ScriptIntegration` configurado para o GTM.
1729
+ * @param {GoogleTagManagerConfig} config Configuração com `containerId` e `dataLayerName` opcional.
1730
+ * @returns {ScriptIntegration} Integração tipada com `category: 'analytics'`.
1700
1731
  */
1701
1732
  declare function createGoogleTagManagerIntegration(config: GoogleTagManagerConfig): ScriptIntegration;
1702
1733
  /**
1703
1734
  * @function
1704
1735
  * @category Utils
1705
1736
  * @since 0.2.0
1706
- * Cria um objeto de integração para o widget de acessibilidade UserWay.
1737
+ * Cria uma integração para o widget de acessibilidade UserWay.
1707
1738
  *
1708
- * @param {UserWayConfig} config A configuração do UserWay, incluindo o `accountId`.
1709
- * @returns {ScriptIntegration} Um objeto `ScriptIntegration` configurado para o UserWay.
1739
+ * @param {UserWayConfig} config Configuração com `accountId`.
1740
+ * @returns {ScriptIntegration} Integração tipada com `category: 'functional'`.
1710
1741
  */
1711
1742
  declare function createUserWayIntegration(config: UserWayConfig): ScriptIntegration;
1712
1743
  /**
@@ -2101,8 +2132,10 @@ declare function FloatingPreferencesButton({ position, offset, icon, tooltip, Fa
2101
2132
  * @returns Um objeto `ConsentPreferences` com as categorias e seus valores iniciais.
2102
2133
  * @remarks
2103
2134
  * Esta função é crucial para inicializar o estado de consentimento. Ela garante que apenas as categorias
2104
- * definidas no `ConsentProvider` sejam incluídas no objeto de preferências, alinhando-se ao princípio
2105
- * de minimização de dados da LGPD.
2135
+ * definidas no `ConsentProvider` sejam incluídas no objeto de preferências (tanto categorias padrão
2136
+ * em `enabledCategories` quanto `customCategories`), alinhando-se ao princípio de minimização de dados da LGPD.
2137
+ *
2138
+ * Since v0.4.0: inclui categorias de `config.customCategories` na inicialização.
2106
2139
  * @example
2107
2140
  * ```ts
2108
2141
  * // Gera preferências com 'analytics' e 'marketing' desabilitados por padrão
@@ -2111,6 +2144,15 @@ declare function FloatingPreferencesButton({ position, offset, icon, tooltip, Fa
2111
2144
  * })
2112
2145
  * // Result: { necessary: true, analytics: false, marketing: false }
2113
2146
  *
2147
+ * // Inclui categorias customizadas
2148
+ * const initialWithCustom = createProjectPreferences({
2149
+ * enabledCategories: ['analytics'],
2150
+ * customCategories: [
2151
+ * { id: 'abTesting', name: 'AB Testing', description: 'Experimentos de interface' },
2152
+ * ],
2153
+ * })
2154
+ * // Result: { necessary: true, analytics: false, abTesting: false }
2155
+ *
2114
2156
  * // Gera preferências com todas as categorias habilitadas
2115
2157
  * const allAcceptedPrefs = createProjectPreferences(
2116
2158
  * { enabledCategories: ['analytics', 'marketing'] },
@@ -2131,6 +2173,8 @@ declare function createProjectPreferences(config?: ProjectCategoriesConfig, defa
2131
2173
  * Garante a integridade dos dados ao carregar o estado de um cookie. Se a configuração do projeto mudou
2132
2174
  * (ex: uma categoria foi removida), esta função limpa as preferências obsoletas do estado,
2133
2175
  * evitando inconsistências.
2176
+ *
2177
+ * Since v0.4.0: reconhece `config.customCategories` como válidas ao validar.
2134
2178
  * @example
2135
2179
  * ```ts
2136
2180
  * const savedPrefs = { necessary: true, analytics: true, oldCategory: false }
@@ -2149,7 +2193,10 @@ declare function validateProjectPreferences(preferences: ConsentPreferences, con
2149
2193
  * @returns Um array de objetos `CategoryDefinition`.
2150
2194
  * @remarks
2151
2195
  * Útil para construir UIs de preferência customizadas, pois fornece os nomes e descrições
2152
- * de todas as categorias que devem ser exibidas ao usuário.
2196
+ * de todas as categorias que devem ser exibidas ao usuário, incluindo quaisquer `customCategories`
2197
+ * definidas no `ConsentProvider`.
2198
+ *
2199
+ * Since v0.4.0: inclui categorias definidas em `config.customCategories`.
2153
2200
  * @example
2154
2201
  * ```ts
2155
2202
  * const config = { enabledCategories: ['analytics'] }