@react-lgpd-consent/core 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -93,7 +93,7 @@ declare const GUIDANCE_PRESETS: {
93
93
 
94
94
  /**
95
95
  * @fileoverview
96
- * Definições de tipos TypeScript para o sistema de consentimento LGPD/ANPD.
96
+ * Definições de tipos TypeScript para o sistema de consentimento LGPD.
97
97
  *
98
98
  * Este arquivo contém todas as interfaces, tipos e estruturas de dados utilizadas
99
99
  * pela biblioteca react-lgpd-consent, incluindo definições de categorias,
@@ -376,7 +376,7 @@ interface ConsentPreferences {
376
376
  [key: string]: boolean;
377
377
  }
378
378
  /**
379
- * Estrutura do cookie de consentimento em conformidade com LGPD/ANPD.
379
+ * Estrutura do cookie de consentimento em conformidade com LGPD.
380
380
  * @category Types
381
381
  * @since 0.2.1
382
382
  *
@@ -686,14 +686,22 @@ interface ConsentTexts {
686
686
  interface ConsentCookieOptions {
687
687
  /** Nome do cookie. Padrão: 'cookieConsent' */
688
688
  name: string;
689
- /** Tempo de expiração em dias. Padrão: 365 */
690
- maxAgeDays: number;
689
+ /**
690
+ * Tempo de expiração em segundos.
691
+ * @defaultValue 31536000 (365 dias)
692
+ */
693
+ maxAge?: number;
694
+ /**
695
+ * Tempo de expiração em dias (legado).
696
+ * @deprecated Prefira `maxAge` em segundos.
697
+ */
698
+ maxAgeDays?: number;
691
699
  /** Política SameSite do cookie. */
692
- sameSite: 'Lax' | 'Strict';
693
- /** Se o cookie deve ser seguro (HTTPS). Padrão: true */
694
- secure: boolean;
700
+ sameSite?: 'Lax' | 'Strict' | 'None';
701
+ /** Se o cookie deve ser seguro (HTTPS). Padrão: true em HTTPS. */
702
+ secure?: boolean;
695
703
  /** Caminho do cookie. Padrão: '/' */
696
- path: string;
704
+ path?: string;
697
705
  /**
698
706
  * Domínio do cookie (ex.: `.example.com` para compartilhar entre subdomínios).
699
707
  * Se não definido, o navegador usa o domínio atual.
@@ -1391,8 +1399,9 @@ interface ConsentProviderProps {
1391
1399
  * ```tsx
1392
1400
  * cookie={{
1393
1401
  * name: 'meuAppConsent',
1394
- * maxAgeDays: 180,
1395
- * sameSite: 'Strict'
1402
+ * maxAge: 60 * 60 * 24 * 180, // 180 dias
1403
+ * sameSite: 'Strict',
1404
+ * secure: true,
1396
1405
  * }}
1397
1406
  * ```
1398
1407
  */
@@ -1616,6 +1625,8 @@ interface ConsentInitializedEvent {
1616
1625
  timestamp: string;
1617
1626
  /** Estado inicial das categorias de consentimento */
1618
1627
  categories: Record<string, boolean>;
1628
+ /** Snapshot das preferências (alias para categories para Consent Mode v2) */
1629
+ preferences?: Record<string, boolean>;
1619
1630
  }
1620
1631
  /**
1621
1632
  * Payload do evento `consent_updated` disparado no dataLayer.
@@ -1657,6 +1668,8 @@ interface ConsentUpdatedEvent {
1657
1668
  origin: ConsentEventOrigin;
1658
1669
  /** Estado atualizado das categorias de consentimento */
1659
1670
  categories: Record<string, boolean>;
1671
+ /** Snapshot das preferências (alias para categories para Consent Mode v2) */
1672
+ preferences?: Record<string, boolean>;
1660
1673
  /** Lista de categorias que foram modificadas nesta atualização */
1661
1674
  changed_categories: string[];
1662
1675
  }
@@ -2429,6 +2442,18 @@ declare function createConsentAuditEntry(state: ConsentState, params: {
2429
2442
  * Fornece funções para carregar scripts de terceiros de forma condicional ao consentimento LGPD,
2430
2443
  * garantindo compatibilidade SSR e verificações de permissões por categoria.
2431
2444
  */
2445
+
2446
+ type ConsentSnapshot = {
2447
+ consented: boolean;
2448
+ preferences: ConsentPreferences;
2449
+ isModalOpen?: boolean;
2450
+ };
2451
+ interface LoadScriptOptions {
2452
+ consentSnapshot?: ConsentSnapshot;
2453
+ cookieName?: string;
2454
+ pollIntervalMs?: number;
2455
+ skipConsentCheck?: boolean;
2456
+ }
2432
2457
  /**
2433
2458
  * @function
2434
2459
  * @category Utils
@@ -2448,6 +2473,7 @@ declare function createConsentAuditEntry(state: ConsentState, params: {
2448
2473
  * @param {string | null} [category=null] A categoria de consentimento exigida para o script. Suporta tanto categorias predefinidas quanto customizadas. Se o consentimento para esta categoria não for dado, o script não será carregado.
2449
2474
  * @param {Record<string, string>} [attrs={}] Atributos adicionais a serem aplicados ao elemento `<script>` (ex: `{ async: 'true' }`).
2450
2475
  * @param {string | undefined} [nonce] Nonce CSP opcional aplicado ao script.
2476
+ * @param {LoadScriptOptions} [options] Configurações avançadas (consentSnapshot, cookieName, pollIntervalMs, skipConsentCheck).
2451
2477
  * @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.
2452
2478
  * @example
2453
2479
  * ```ts
@@ -2457,7 +2483,7 @@ declare function createConsentAuditEntry(state: ConsentState, params: {
2457
2483
  * .catch(error => console.error('Erro ao carregar script:', error))
2458
2484
  * ```
2459
2485
  */
2460
- declare function loadScript(id: string, src: string, category?: string | null, attrs?: Record<string, string>, nonce?: string): Promise<void>;
2486
+ declare function loadScript(id: string, src: string, category?: string | null, attrs?: Record<string, string>, nonce?: string, options?: LoadScriptOptions): Promise<void>;
2461
2487
 
2462
2488
  /**
2463
2489
  * Utilitários para descoberta e categorização de cookies em tempo de execução (experimental).
@@ -2515,6 +2541,7 @@ declare function categorizeDiscoveredCookies(discovered?: CookieDescriptor[], re
2515
2541
  * - URLs possuem valores default atualizados e podem ser sobrescritos via `scriptUrl`
2516
2542
  * - SSR-safe: toda execução que toca `window` é protegida
2517
2543
  */
2544
+
2518
2545
  /**
2519
2546
  * Integração de script de terceiros condicionada a consentimento.
2520
2547
  *
@@ -2561,6 +2588,15 @@ interface ScriptIntegration {
2561
2588
  attrs?: Record<string, string>;
2562
2589
  /** Nonce CSP opcional aplicado à tag script */
2563
2590
  nonce?: string;
2591
+ /** Prioridade para ordenação na fila do loader (maior = executa primeiro dentro da categoria) */
2592
+ priority?: number;
2593
+ /** Rotina opcional executada antes do carregamento principal (ex.: bootstrap de Consent Mode) */
2594
+ bootstrap?: () => void | Promise<void>;
2595
+ /** Callback disparado quando o consentimento é atualizado */
2596
+ onConsentUpdate?: (consent: {
2597
+ consented: boolean;
2598
+ preferences: ConsentPreferences;
2599
+ }) => void;
2564
2600
  /** Lista de cookies que o script pode definir */
2565
2601
  cookies?: string[];
2566
2602
  /** Informações detalhadas dos cookies (nome, finalidade, duração, fornecedor) */
@@ -3204,6 +3240,32 @@ declare function suggestCategoryForScript(name: string): string[];
3204
3240
  * Facilita integração com ferramentas como Google Analytics, Tag Manager, etc.
3205
3241
  */
3206
3242
 
3243
+ interface RegisteredScript {
3244
+ id: string;
3245
+ category: string;
3246
+ execute: () => void | Promise<void>;
3247
+ priority?: number;
3248
+ allowReload?: boolean;
3249
+ onConsentUpdate?: (consent: {
3250
+ consented: boolean;
3251
+ preferences: ConsentPreferences;
3252
+ }) => void;
3253
+ }
3254
+ /**
3255
+ * Registra um script (inline ou externo) na fila controlada por consentimento.
3256
+ *
3257
+ * @remarks
3258
+ * - Scripts `necessary` rodam imediatamente; demais aguardam consentimento da categoria.
3259
+ * - Fluxo de estados: `pending` → `running` → `executed` (respeitando `allowReload` e `onConsentUpdate`).
3260
+ * - A fila é ordenada por categoria, `priority` (maior primeiro) e ordem de registro.
3261
+ * - `allowReload` permite reexecutar scripts quando o usuário muda preferências.
3262
+ * - Use `onConsentUpdate` para reenviar sinais (ex.: Consent Mode) após novas decisões.
3263
+ * - Sempre chame o cleanup retornado em efeitos React para evitar múltiplos registros do mesmo `id`.
3264
+ *
3265
+ * @param def Definição do script a ser registrado.
3266
+ * @returns Função de cleanup para remover o script da fila.
3267
+ */
3268
+ declare function registerScript(def: RegisteredScript): () => void;
3207
3269
  interface ConsentScriptLoaderProps {
3208
3270
  /** Lista de integrações de scripts para carregar baseado no consentimento */
3209
3271
  integrations: ScriptIntegration[];
@@ -3435,7 +3497,7 @@ type LanguageTexts = Partial<Omit<ConsentTexts, 'i18n' | 'variants' | 'contexts'
3435
3497
  *
3436
3498
  * Interface expandida que permite personalização granular de todas as mensagens da biblioteca.
3437
3499
  * Suporta múltiplos idiomas, contextos específicos (e-commerce, SaaS, governo), variações
3438
- * de tom, e compliance completo com LGPD/ANPD.
3500
+ * de tom, e compliance completo com LGPD.
3439
3501
  *
3440
3502
  * @category Types
3441
3503
  * @since 0.4.1
@@ -3843,6 +3905,98 @@ interface PeerDepsCheckResult {
3843
3905
  /** Lista de erros críticos detectados */
3844
3906
  errors: string[];
3845
3907
  }
3908
+ /**
3909
+ * Idiomas suportados para mensagens de diagnóstico de peer dependencies.
3910
+ *
3911
+ * @category Utils
3912
+ * @since 0.7.1
3913
+ */
3914
+ type PeerDepsLocale = 'pt-BR' | 'en';
3915
+ /**
3916
+ * Estrutura de mensagens de erro e aviso para diagnóstico de peer dependencies.
3917
+ *
3918
+ * @category Utils
3919
+ * @since 0.7.1
3920
+ */
3921
+ interface PeerDepsMessages {
3922
+ MULTIPLE_REACT_INSTANCES: string;
3923
+ UNSUPPORTED_REACT_VERSION: (version: string) => string;
3924
+ UNSUPPORTED_MUI_VERSION: (version: string) => string;
3925
+ MUI_OUT_OF_RANGE: (version: string) => string;
3926
+ }
3927
+ /**
3928
+ * Define o idioma para mensagens de diagnóstico de peer dependencies.
3929
+ *
3930
+ * @category Utils
3931
+ * @since 0.7.1
3932
+ *
3933
+ * @param locale - Idioma desejado ('pt-BR' ou 'en')
3934
+ *
3935
+ * @example
3936
+ * ```typescript
3937
+ * import { setPeerDepsLocale } from '@react-lgpd-consent/core'
3938
+ *
3939
+ * // Configurar mensagens em inglês
3940
+ * setPeerDepsLocale('en')
3941
+ * ```
3942
+ */
3943
+ declare function setPeerDepsLocale(locale: PeerDepsLocale): void;
3944
+ /**
3945
+ * Obtém o idioma atual configurado para mensagens de diagnóstico.
3946
+ *
3947
+ * @category Utils
3948
+ * @since 0.7.1
3949
+ *
3950
+ * @returns O idioma atual
3951
+ *
3952
+ * @example
3953
+ * ```typescript
3954
+ * import { getPeerDepsLocale } from '@react-lgpd-consent/core'
3955
+ *
3956
+ * const locale = getPeerDepsLocale() // 'pt-BR' ou 'en'
3957
+ * ```
3958
+ */
3959
+ declare function getPeerDepsLocale(): PeerDepsLocale;
3960
+ /**
3961
+ * Permite sobrescrever mensagens de diagnóstico com versões customizadas.
3962
+ * Útil para traduzir para outros idiomas ou personalizar o texto.
3963
+ *
3964
+ * @category Utils
3965
+ * @since 0.7.1
3966
+ *
3967
+ * @param messages - Objeto parcial com mensagens a sobrescrever
3968
+ *
3969
+ * @remarks
3970
+ * As mensagens customizadas têm prioridade sobre as mensagens padrão.
3971
+ * Pode fornecer apenas as mensagens que deseja sobrescrever.
3972
+ *
3973
+ * @example
3974
+ * ```typescript
3975
+ * import { setPeerDepsMessages } from '@react-lgpd-consent/core'
3976
+ *
3977
+ * // Customizar mensagens em espanhol
3978
+ * setPeerDepsMessages({
3979
+ * MULTIPLE_REACT_INSTANCES: `ERROR: Múltiples instancias de React detectadas...`,
3980
+ * UNSUPPORTED_REACT_VERSION: (v) => `Versión ${v} no soportada...`,
3981
+ * })
3982
+ * ```
3983
+ */
3984
+ declare function setPeerDepsMessages(messages: Partial<PeerDepsMessages>): void;
3985
+ /**
3986
+ * Restaura as mensagens padrão, removendo qualquer customização.
3987
+ *
3988
+ * @category Utils
3989
+ * @since 0.7.1
3990
+ *
3991
+ * @example
3992
+ * ```typescript
3993
+ * import { resetPeerDepsMessages } from '@react-lgpd-consent/core'
3994
+ *
3995
+ * // Voltar para mensagens padrão
3996
+ * resetPeerDepsMessages()
3997
+ * ```
3998
+ */
3999
+ declare function resetPeerDepsMessages(): void;
3846
4000
  /**
3847
4001
  * Verifica compatibilidade de peer dependencies (React e MUI).
3848
4002
  *
@@ -4145,4 +4299,4 @@ declare function useDataLayerEvents(): {
4145
4299
  pushUpdated: typeof pushConsentUpdatedEvent;
4146
4300
  };
4147
4301
 
4148
- export { ANPD_CATEGORY_PRESETS, type AdvancedConsentTexts, type AnpdPresetCategory, COMMON_INTEGRATIONS, type CategoriesContextValue, type Category, type CategoryAutoConfigResult, type CategoryDefinition, type ClarityConfig, type ConsentAuditAction, type ConsentAuditEntry, type ConsentContextValue, type ConsentCookieData, type ConsentCookieOptions, type ConsentEvent, type ConsentEventOrigin, ConsentGate, type ConsentInitializedEvent, type ConsentPreferences, ConsentProvider, type ConsentProviderProps, ConsentScriptLoader, type ConsentScriptLoaderProps, type ConsentState, type ConsentStorageConfig, type ConsentTexts, type ConsentUpdatedEvent, type ConsentVersionChangeContext, type CookieDescriptor, type CorporateConfig, type CreateAnpdCategoriesOptions, type CustomCookieBannerProps, type CustomFloatingPreferencesButtonProps, type CustomPreferencesModalProps, DEFAULT_PROJECT_CATEGORIES, DesignProvider, type DesignTokens, type DeveloperGuidance, type ECommerceConfig, EXPANDED_DEFAULT_TEXTS, type FacebookPixelConfig, GUIDANCE_PRESETS, type GoogleAnalyticsConfig, type GoogleTagManagerConfig, type GuidanceConfig, type GuidanceMessage, type GuidanceSeverity, type HotjarConfig, INTEGRATION_TEMPLATES, type IntercomConfig, LogLevel, type MixpanelConfig, type PeerDepsCheckResult, type ProjectCategoriesConfig, type SaaSConfig, type ScriptIntegration, TEXT_TEMPLATES, type UserWayConfig, type ZendeskConfig, analyzeDeveloperConfiguration, analyzeIntegrationCategories, autoConfigureCategories, buildConsentStorageKey, categorizeDiscoveredCookies, checkPeerDeps, createAnpdCategoriesConfig, createClarityIntegration, createConsentAuditEntry, createCorporateIntegrations, createECommerceIntegrations, createFacebookPixelIntegration, createGoogleAnalyticsIntegration, createGoogleTagManagerIntegration, createHotjarIntegration, createIntercomIntegration, createMixpanelIntegration, createProjectPreferences, createSaaSIntegrations, createUserWayIntegration, createZendeskChatIntegration, defaultTexts, detectConsentCookieName, discoverRuntimeCookies, ensureNecessaryAlwaysOn, extractCategoriesFromIntegrations, getAllProjectCategories, getCookiesInfoForCategory, loadScript, logDeveloperGuidance, logger, openPreferencesModal, pushConsentInitializedEvent, pushConsentUpdatedEvent, resolveTexts, runPeerDepsCheck, setCookieCatalogOverrides, setCookieCategoryOverrides, setDebugLogging, suggestCategoryForScript, useCategories, useCategoryStatus, useConsent, useConsentHydration, useConsentScriptLoader, useConsentTexts, useDataLayerEvents, useDesignTokens, useDeveloperGuidance, useOpenPreferencesModal, validateIntegrationCategories, validateNecessaryClassification, validateProjectPreferences };
4302
+ export { ANPD_CATEGORY_PRESETS, type AdvancedConsentTexts, type AnpdPresetCategory, COMMON_INTEGRATIONS, type CategoriesContextValue, type Category, type CategoryAutoConfigResult, type CategoryDefinition, type ClarityConfig, type ConsentAuditAction, type ConsentAuditEntry, type ConsentContextValue, type ConsentCookieData, type ConsentCookieOptions, type ConsentEvent, type ConsentEventOrigin, ConsentGate, type ConsentInitializedEvent, type ConsentPreferences, ConsentProvider, type ConsentProviderProps, ConsentScriptLoader, type ConsentScriptLoaderProps, type ConsentState, type ConsentStorageConfig, type ConsentTexts, type ConsentUpdatedEvent, type ConsentVersionChangeContext, type CookieDescriptor, type CorporateConfig, type CreateAnpdCategoriesOptions, type CustomCookieBannerProps, type CustomFloatingPreferencesButtonProps, type CustomPreferencesModalProps, DEFAULT_PROJECT_CATEGORIES, DesignProvider, type DesignTokens, type DeveloperGuidance, type ECommerceConfig, EXPANDED_DEFAULT_TEXTS, type FacebookPixelConfig, GUIDANCE_PRESETS, type GoogleAnalyticsConfig, type GoogleTagManagerConfig, type GuidanceConfig, type GuidanceMessage, type GuidanceSeverity, type HotjarConfig, INTEGRATION_TEMPLATES, type IntercomConfig, LogLevel, type MixpanelConfig, type PeerDepsCheckResult, type PeerDepsLocale, type PeerDepsMessages, type ProjectCategoriesConfig, type RegisteredScript, type SaaSConfig, type ScriptIntegration, TEXT_TEMPLATES, type UserWayConfig, type ZendeskConfig, analyzeDeveloperConfiguration, analyzeIntegrationCategories, autoConfigureCategories, buildConsentStorageKey, categorizeDiscoveredCookies, checkPeerDeps, createAnpdCategoriesConfig, createClarityIntegration, createConsentAuditEntry, createCorporateIntegrations, createECommerceIntegrations, createFacebookPixelIntegration, createGoogleAnalyticsIntegration, createGoogleTagManagerIntegration, createHotjarIntegration, createIntercomIntegration, createMixpanelIntegration, createProjectPreferences, createSaaSIntegrations, createUserWayIntegration, createZendeskChatIntegration, defaultTexts, detectConsentCookieName, discoverRuntimeCookies, ensureNecessaryAlwaysOn, extractCategoriesFromIntegrations, getAllProjectCategories, getCookiesInfoForCategory, getPeerDepsLocale, loadScript, logDeveloperGuidance, logger, openPreferencesModal, pushConsentInitializedEvent, pushConsentUpdatedEvent, registerScript, resetPeerDepsMessages, resolveTexts, runPeerDepsCheck, setCookieCatalogOverrides, setCookieCategoryOverrides, setDebugLogging, setPeerDepsLocale, setPeerDepsMessages, suggestCategoryForScript, useCategories, useCategoryStatus, useConsent, useConsentHydration, useConsentScriptLoader, useConsentTexts, useDataLayerEvents, useDesignTokens, useDeveloperGuidance, useOpenPreferencesModal, validateIntegrationCategories, validateNecessaryClassification, validateProjectPreferences };
package/dist/index.d.ts CHANGED
@@ -93,7 +93,7 @@ declare const GUIDANCE_PRESETS: {
93
93
 
94
94
  /**
95
95
  * @fileoverview
96
- * Definições de tipos TypeScript para o sistema de consentimento LGPD/ANPD.
96
+ * Definições de tipos TypeScript para o sistema de consentimento LGPD.
97
97
  *
98
98
  * Este arquivo contém todas as interfaces, tipos e estruturas de dados utilizadas
99
99
  * pela biblioteca react-lgpd-consent, incluindo definições de categorias,
@@ -376,7 +376,7 @@ interface ConsentPreferences {
376
376
  [key: string]: boolean;
377
377
  }
378
378
  /**
379
- * Estrutura do cookie de consentimento em conformidade com LGPD/ANPD.
379
+ * Estrutura do cookie de consentimento em conformidade com LGPD.
380
380
  * @category Types
381
381
  * @since 0.2.1
382
382
  *
@@ -686,14 +686,22 @@ interface ConsentTexts {
686
686
  interface ConsentCookieOptions {
687
687
  /** Nome do cookie. Padrão: 'cookieConsent' */
688
688
  name: string;
689
- /** Tempo de expiração em dias. Padrão: 365 */
690
- maxAgeDays: number;
689
+ /**
690
+ * Tempo de expiração em segundos.
691
+ * @defaultValue 31536000 (365 dias)
692
+ */
693
+ maxAge?: number;
694
+ /**
695
+ * Tempo de expiração em dias (legado).
696
+ * @deprecated Prefira `maxAge` em segundos.
697
+ */
698
+ maxAgeDays?: number;
691
699
  /** Política SameSite do cookie. */
692
- sameSite: 'Lax' | 'Strict';
693
- /** Se o cookie deve ser seguro (HTTPS). Padrão: true */
694
- secure: boolean;
700
+ sameSite?: 'Lax' | 'Strict' | 'None';
701
+ /** Se o cookie deve ser seguro (HTTPS). Padrão: true em HTTPS. */
702
+ secure?: boolean;
695
703
  /** Caminho do cookie. Padrão: '/' */
696
- path: string;
704
+ path?: string;
697
705
  /**
698
706
  * Domínio do cookie (ex.: `.example.com` para compartilhar entre subdomínios).
699
707
  * Se não definido, o navegador usa o domínio atual.
@@ -1391,8 +1399,9 @@ interface ConsentProviderProps {
1391
1399
  * ```tsx
1392
1400
  * cookie={{
1393
1401
  * name: 'meuAppConsent',
1394
- * maxAgeDays: 180,
1395
- * sameSite: 'Strict'
1402
+ * maxAge: 60 * 60 * 24 * 180, // 180 dias
1403
+ * sameSite: 'Strict',
1404
+ * secure: true,
1396
1405
  * }}
1397
1406
  * ```
1398
1407
  */
@@ -1616,6 +1625,8 @@ interface ConsentInitializedEvent {
1616
1625
  timestamp: string;
1617
1626
  /** Estado inicial das categorias de consentimento */
1618
1627
  categories: Record<string, boolean>;
1628
+ /** Snapshot das preferências (alias para categories para Consent Mode v2) */
1629
+ preferences?: Record<string, boolean>;
1619
1630
  }
1620
1631
  /**
1621
1632
  * Payload do evento `consent_updated` disparado no dataLayer.
@@ -1657,6 +1668,8 @@ interface ConsentUpdatedEvent {
1657
1668
  origin: ConsentEventOrigin;
1658
1669
  /** Estado atualizado das categorias de consentimento */
1659
1670
  categories: Record<string, boolean>;
1671
+ /** Snapshot das preferências (alias para categories para Consent Mode v2) */
1672
+ preferences?: Record<string, boolean>;
1660
1673
  /** Lista de categorias que foram modificadas nesta atualização */
1661
1674
  changed_categories: string[];
1662
1675
  }
@@ -2429,6 +2442,18 @@ declare function createConsentAuditEntry(state: ConsentState, params: {
2429
2442
  * Fornece funções para carregar scripts de terceiros de forma condicional ao consentimento LGPD,
2430
2443
  * garantindo compatibilidade SSR e verificações de permissões por categoria.
2431
2444
  */
2445
+
2446
+ type ConsentSnapshot = {
2447
+ consented: boolean;
2448
+ preferences: ConsentPreferences;
2449
+ isModalOpen?: boolean;
2450
+ };
2451
+ interface LoadScriptOptions {
2452
+ consentSnapshot?: ConsentSnapshot;
2453
+ cookieName?: string;
2454
+ pollIntervalMs?: number;
2455
+ skipConsentCheck?: boolean;
2456
+ }
2432
2457
  /**
2433
2458
  * @function
2434
2459
  * @category Utils
@@ -2448,6 +2473,7 @@ declare function createConsentAuditEntry(state: ConsentState, params: {
2448
2473
  * @param {string | null} [category=null] A categoria de consentimento exigida para o script. Suporta tanto categorias predefinidas quanto customizadas. Se o consentimento para esta categoria não for dado, o script não será carregado.
2449
2474
  * @param {Record<string, string>} [attrs={}] Atributos adicionais a serem aplicados ao elemento `<script>` (ex: `{ async: 'true' }`).
2450
2475
  * @param {string | undefined} [nonce] Nonce CSP opcional aplicado ao script.
2476
+ * @param {LoadScriptOptions} [options] Configurações avançadas (consentSnapshot, cookieName, pollIntervalMs, skipConsentCheck).
2451
2477
  * @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.
2452
2478
  * @example
2453
2479
  * ```ts
@@ -2457,7 +2483,7 @@ declare function createConsentAuditEntry(state: ConsentState, params: {
2457
2483
  * .catch(error => console.error('Erro ao carregar script:', error))
2458
2484
  * ```
2459
2485
  */
2460
- declare function loadScript(id: string, src: string, category?: string | null, attrs?: Record<string, string>, nonce?: string): Promise<void>;
2486
+ declare function loadScript(id: string, src: string, category?: string | null, attrs?: Record<string, string>, nonce?: string, options?: LoadScriptOptions): Promise<void>;
2461
2487
 
2462
2488
  /**
2463
2489
  * Utilitários para descoberta e categorização de cookies em tempo de execução (experimental).
@@ -2515,6 +2541,7 @@ declare function categorizeDiscoveredCookies(discovered?: CookieDescriptor[], re
2515
2541
  * - URLs possuem valores default atualizados e podem ser sobrescritos via `scriptUrl`
2516
2542
  * - SSR-safe: toda execução que toca `window` é protegida
2517
2543
  */
2544
+
2518
2545
  /**
2519
2546
  * Integração de script de terceiros condicionada a consentimento.
2520
2547
  *
@@ -2561,6 +2588,15 @@ interface ScriptIntegration {
2561
2588
  attrs?: Record<string, string>;
2562
2589
  /** Nonce CSP opcional aplicado à tag script */
2563
2590
  nonce?: string;
2591
+ /** Prioridade para ordenação na fila do loader (maior = executa primeiro dentro da categoria) */
2592
+ priority?: number;
2593
+ /** Rotina opcional executada antes do carregamento principal (ex.: bootstrap de Consent Mode) */
2594
+ bootstrap?: () => void | Promise<void>;
2595
+ /** Callback disparado quando o consentimento é atualizado */
2596
+ onConsentUpdate?: (consent: {
2597
+ consented: boolean;
2598
+ preferences: ConsentPreferences;
2599
+ }) => void;
2564
2600
  /** Lista de cookies que o script pode definir */
2565
2601
  cookies?: string[];
2566
2602
  /** Informações detalhadas dos cookies (nome, finalidade, duração, fornecedor) */
@@ -3204,6 +3240,32 @@ declare function suggestCategoryForScript(name: string): string[];
3204
3240
  * Facilita integração com ferramentas como Google Analytics, Tag Manager, etc.
3205
3241
  */
3206
3242
 
3243
+ interface RegisteredScript {
3244
+ id: string;
3245
+ category: string;
3246
+ execute: () => void | Promise<void>;
3247
+ priority?: number;
3248
+ allowReload?: boolean;
3249
+ onConsentUpdate?: (consent: {
3250
+ consented: boolean;
3251
+ preferences: ConsentPreferences;
3252
+ }) => void;
3253
+ }
3254
+ /**
3255
+ * Registra um script (inline ou externo) na fila controlada por consentimento.
3256
+ *
3257
+ * @remarks
3258
+ * - Scripts `necessary` rodam imediatamente; demais aguardam consentimento da categoria.
3259
+ * - Fluxo de estados: `pending` → `running` → `executed` (respeitando `allowReload` e `onConsentUpdate`).
3260
+ * - A fila é ordenada por categoria, `priority` (maior primeiro) e ordem de registro.
3261
+ * - `allowReload` permite reexecutar scripts quando o usuário muda preferências.
3262
+ * - Use `onConsentUpdate` para reenviar sinais (ex.: Consent Mode) após novas decisões.
3263
+ * - Sempre chame o cleanup retornado em efeitos React para evitar múltiplos registros do mesmo `id`.
3264
+ *
3265
+ * @param def Definição do script a ser registrado.
3266
+ * @returns Função de cleanup para remover o script da fila.
3267
+ */
3268
+ declare function registerScript(def: RegisteredScript): () => void;
3207
3269
  interface ConsentScriptLoaderProps {
3208
3270
  /** Lista de integrações de scripts para carregar baseado no consentimento */
3209
3271
  integrations: ScriptIntegration[];
@@ -3435,7 +3497,7 @@ type LanguageTexts = Partial<Omit<ConsentTexts, 'i18n' | 'variants' | 'contexts'
3435
3497
  *
3436
3498
  * Interface expandida que permite personalização granular de todas as mensagens da biblioteca.
3437
3499
  * Suporta múltiplos idiomas, contextos específicos (e-commerce, SaaS, governo), variações
3438
- * de tom, e compliance completo com LGPD/ANPD.
3500
+ * de tom, e compliance completo com LGPD.
3439
3501
  *
3440
3502
  * @category Types
3441
3503
  * @since 0.4.1
@@ -3843,6 +3905,98 @@ interface PeerDepsCheckResult {
3843
3905
  /** Lista de erros críticos detectados */
3844
3906
  errors: string[];
3845
3907
  }
3908
+ /**
3909
+ * Idiomas suportados para mensagens de diagnóstico de peer dependencies.
3910
+ *
3911
+ * @category Utils
3912
+ * @since 0.7.1
3913
+ */
3914
+ type PeerDepsLocale = 'pt-BR' | 'en';
3915
+ /**
3916
+ * Estrutura de mensagens de erro e aviso para diagnóstico de peer dependencies.
3917
+ *
3918
+ * @category Utils
3919
+ * @since 0.7.1
3920
+ */
3921
+ interface PeerDepsMessages {
3922
+ MULTIPLE_REACT_INSTANCES: string;
3923
+ UNSUPPORTED_REACT_VERSION: (version: string) => string;
3924
+ UNSUPPORTED_MUI_VERSION: (version: string) => string;
3925
+ MUI_OUT_OF_RANGE: (version: string) => string;
3926
+ }
3927
+ /**
3928
+ * Define o idioma para mensagens de diagnóstico de peer dependencies.
3929
+ *
3930
+ * @category Utils
3931
+ * @since 0.7.1
3932
+ *
3933
+ * @param locale - Idioma desejado ('pt-BR' ou 'en')
3934
+ *
3935
+ * @example
3936
+ * ```typescript
3937
+ * import { setPeerDepsLocale } from '@react-lgpd-consent/core'
3938
+ *
3939
+ * // Configurar mensagens em inglês
3940
+ * setPeerDepsLocale('en')
3941
+ * ```
3942
+ */
3943
+ declare function setPeerDepsLocale(locale: PeerDepsLocale): void;
3944
+ /**
3945
+ * Obtém o idioma atual configurado para mensagens de diagnóstico.
3946
+ *
3947
+ * @category Utils
3948
+ * @since 0.7.1
3949
+ *
3950
+ * @returns O idioma atual
3951
+ *
3952
+ * @example
3953
+ * ```typescript
3954
+ * import { getPeerDepsLocale } from '@react-lgpd-consent/core'
3955
+ *
3956
+ * const locale = getPeerDepsLocale() // 'pt-BR' ou 'en'
3957
+ * ```
3958
+ */
3959
+ declare function getPeerDepsLocale(): PeerDepsLocale;
3960
+ /**
3961
+ * Permite sobrescrever mensagens de diagnóstico com versões customizadas.
3962
+ * Útil para traduzir para outros idiomas ou personalizar o texto.
3963
+ *
3964
+ * @category Utils
3965
+ * @since 0.7.1
3966
+ *
3967
+ * @param messages - Objeto parcial com mensagens a sobrescrever
3968
+ *
3969
+ * @remarks
3970
+ * As mensagens customizadas têm prioridade sobre as mensagens padrão.
3971
+ * Pode fornecer apenas as mensagens que deseja sobrescrever.
3972
+ *
3973
+ * @example
3974
+ * ```typescript
3975
+ * import { setPeerDepsMessages } from '@react-lgpd-consent/core'
3976
+ *
3977
+ * // Customizar mensagens em espanhol
3978
+ * setPeerDepsMessages({
3979
+ * MULTIPLE_REACT_INSTANCES: `ERROR: Múltiples instancias de React detectadas...`,
3980
+ * UNSUPPORTED_REACT_VERSION: (v) => `Versión ${v} no soportada...`,
3981
+ * })
3982
+ * ```
3983
+ */
3984
+ declare function setPeerDepsMessages(messages: Partial<PeerDepsMessages>): void;
3985
+ /**
3986
+ * Restaura as mensagens padrão, removendo qualquer customização.
3987
+ *
3988
+ * @category Utils
3989
+ * @since 0.7.1
3990
+ *
3991
+ * @example
3992
+ * ```typescript
3993
+ * import { resetPeerDepsMessages } from '@react-lgpd-consent/core'
3994
+ *
3995
+ * // Voltar para mensagens padrão
3996
+ * resetPeerDepsMessages()
3997
+ * ```
3998
+ */
3999
+ declare function resetPeerDepsMessages(): void;
3846
4000
  /**
3847
4001
  * Verifica compatibilidade de peer dependencies (React e MUI).
3848
4002
  *
@@ -4145,4 +4299,4 @@ declare function useDataLayerEvents(): {
4145
4299
  pushUpdated: typeof pushConsentUpdatedEvent;
4146
4300
  };
4147
4301
 
4148
- export { ANPD_CATEGORY_PRESETS, type AdvancedConsentTexts, type AnpdPresetCategory, COMMON_INTEGRATIONS, type CategoriesContextValue, type Category, type CategoryAutoConfigResult, type CategoryDefinition, type ClarityConfig, type ConsentAuditAction, type ConsentAuditEntry, type ConsentContextValue, type ConsentCookieData, type ConsentCookieOptions, type ConsentEvent, type ConsentEventOrigin, ConsentGate, type ConsentInitializedEvent, type ConsentPreferences, ConsentProvider, type ConsentProviderProps, ConsentScriptLoader, type ConsentScriptLoaderProps, type ConsentState, type ConsentStorageConfig, type ConsentTexts, type ConsentUpdatedEvent, type ConsentVersionChangeContext, type CookieDescriptor, type CorporateConfig, type CreateAnpdCategoriesOptions, type CustomCookieBannerProps, type CustomFloatingPreferencesButtonProps, type CustomPreferencesModalProps, DEFAULT_PROJECT_CATEGORIES, DesignProvider, type DesignTokens, type DeveloperGuidance, type ECommerceConfig, EXPANDED_DEFAULT_TEXTS, type FacebookPixelConfig, GUIDANCE_PRESETS, type GoogleAnalyticsConfig, type GoogleTagManagerConfig, type GuidanceConfig, type GuidanceMessage, type GuidanceSeverity, type HotjarConfig, INTEGRATION_TEMPLATES, type IntercomConfig, LogLevel, type MixpanelConfig, type PeerDepsCheckResult, type ProjectCategoriesConfig, type SaaSConfig, type ScriptIntegration, TEXT_TEMPLATES, type UserWayConfig, type ZendeskConfig, analyzeDeveloperConfiguration, analyzeIntegrationCategories, autoConfigureCategories, buildConsentStorageKey, categorizeDiscoveredCookies, checkPeerDeps, createAnpdCategoriesConfig, createClarityIntegration, createConsentAuditEntry, createCorporateIntegrations, createECommerceIntegrations, createFacebookPixelIntegration, createGoogleAnalyticsIntegration, createGoogleTagManagerIntegration, createHotjarIntegration, createIntercomIntegration, createMixpanelIntegration, createProjectPreferences, createSaaSIntegrations, createUserWayIntegration, createZendeskChatIntegration, defaultTexts, detectConsentCookieName, discoverRuntimeCookies, ensureNecessaryAlwaysOn, extractCategoriesFromIntegrations, getAllProjectCategories, getCookiesInfoForCategory, loadScript, logDeveloperGuidance, logger, openPreferencesModal, pushConsentInitializedEvent, pushConsentUpdatedEvent, resolveTexts, runPeerDepsCheck, setCookieCatalogOverrides, setCookieCategoryOverrides, setDebugLogging, suggestCategoryForScript, useCategories, useCategoryStatus, useConsent, useConsentHydration, useConsentScriptLoader, useConsentTexts, useDataLayerEvents, useDesignTokens, useDeveloperGuidance, useOpenPreferencesModal, validateIntegrationCategories, validateNecessaryClassification, validateProjectPreferences };
4302
+ export { ANPD_CATEGORY_PRESETS, type AdvancedConsentTexts, type AnpdPresetCategory, COMMON_INTEGRATIONS, type CategoriesContextValue, type Category, type CategoryAutoConfigResult, type CategoryDefinition, type ClarityConfig, type ConsentAuditAction, type ConsentAuditEntry, type ConsentContextValue, type ConsentCookieData, type ConsentCookieOptions, type ConsentEvent, type ConsentEventOrigin, ConsentGate, type ConsentInitializedEvent, type ConsentPreferences, ConsentProvider, type ConsentProviderProps, ConsentScriptLoader, type ConsentScriptLoaderProps, type ConsentState, type ConsentStorageConfig, type ConsentTexts, type ConsentUpdatedEvent, type ConsentVersionChangeContext, type CookieDescriptor, type CorporateConfig, type CreateAnpdCategoriesOptions, type CustomCookieBannerProps, type CustomFloatingPreferencesButtonProps, type CustomPreferencesModalProps, DEFAULT_PROJECT_CATEGORIES, DesignProvider, type DesignTokens, type DeveloperGuidance, type ECommerceConfig, EXPANDED_DEFAULT_TEXTS, type FacebookPixelConfig, GUIDANCE_PRESETS, type GoogleAnalyticsConfig, type GoogleTagManagerConfig, type GuidanceConfig, type GuidanceMessage, type GuidanceSeverity, type HotjarConfig, INTEGRATION_TEMPLATES, type IntercomConfig, LogLevel, type MixpanelConfig, type PeerDepsCheckResult, type PeerDepsLocale, type PeerDepsMessages, type ProjectCategoriesConfig, type RegisteredScript, type SaaSConfig, type ScriptIntegration, TEXT_TEMPLATES, type UserWayConfig, type ZendeskConfig, analyzeDeveloperConfiguration, analyzeIntegrationCategories, autoConfigureCategories, buildConsentStorageKey, categorizeDiscoveredCookies, checkPeerDeps, createAnpdCategoriesConfig, createClarityIntegration, createConsentAuditEntry, createCorporateIntegrations, createECommerceIntegrations, createFacebookPixelIntegration, createGoogleAnalyticsIntegration, createGoogleTagManagerIntegration, createHotjarIntegration, createIntercomIntegration, createMixpanelIntegration, createProjectPreferences, createSaaSIntegrations, createUserWayIntegration, createZendeskChatIntegration, defaultTexts, detectConsentCookieName, discoverRuntimeCookies, ensureNecessaryAlwaysOn, extractCategoriesFromIntegrations, getAllProjectCategories, getCookiesInfoForCategory, getPeerDepsLocale, loadScript, logDeveloperGuidance, logger, openPreferencesModal, pushConsentInitializedEvent, pushConsentUpdatedEvent, registerScript, resetPeerDepsMessages, resolveTexts, runPeerDepsCheck, setCookieCatalogOverrides, setCookieCategoryOverrides, setDebugLogging, setPeerDepsLocale, setPeerDepsMessages, suggestCategoryForScript, useCategories, useCategoryStatus, useConsent, useConsentHydration, useConsentScriptLoader, useConsentTexts, useDataLayerEvents, useDesignTokens, useDeveloperGuidance, useOpenPreferencesModal, validateIntegrationCategories, validateNecessaryClassification, validateProjectPreferences };