react-lgpd-consent 0.4.4 → 0.5.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.js CHANGED
@@ -1,930 +1 @@
1
- export { FloatingPreferencesButton } from './chunk-PJFGQMCI.js';
2
- export { PreferencesModal } from './chunk-N3QOW4SA.js';
3
- import { useConsent, useCategories, logger } from './chunk-RWT2ORFE.js';
4
- export { ConsentProvider, CookieBanner, DEFAULT_PROJECT_CATEGORIES, GUIDANCE_PRESETS, LogLevel, analyzeDeveloperConfiguration, categorizeDiscoveredCookies, createProjectPreferences, defaultTexts, detectConsentCookieName, discoverRuntimeCookies, getAllProjectCategories, getCookiesInfoForCategory, logDeveloperGuidance, openPreferencesModal, setCookieCatalogOverrides, setCookieCategoryOverrides, setDebugLogging, useCategories, useCategoryStatus, useConsent, useConsentHydration, useConsentTexts, useDeveloperGuidance, useOpenPreferencesModal, validateProjectPreferences } from './chunk-RWT2ORFE.js';
5
- import { jsx, Fragment } from 'react/jsx-runtime';
6
- import { createTheme } from '@mui/material/styles';
7
- import * as React from 'react';
8
-
9
- // react-lgpd-consent - Tree-shakeable ESM build
10
- function ConsentGate(props) {
11
- const { preferences } = useConsent();
12
- if (!preferences[props.category]) return null;
13
- return /* @__PURE__ */ jsx(Fragment, { children: props.children });
14
- }
15
-
16
- // src/utils/scriptLoader.ts
17
- function loadScript(id, src, category = null, attrs = {}) {
18
- if (typeof document === "undefined") return Promise.resolve();
19
- if (document.getElementById(id)) return Promise.resolve();
20
- return new Promise((resolve, reject) => {
21
- const checkConsent = () => {
22
- const consentCookie = document.cookie.split("; ").find((row) => row.startsWith("cookieConsent="))?.split("=")[1];
23
- if (!consentCookie) {
24
- setTimeout(checkConsent, 100);
25
- return;
26
- }
27
- try {
28
- const consent = JSON.parse(decodeURIComponent(consentCookie));
29
- if (!consent.consented || consent.isModalOpen) {
30
- setTimeout(checkConsent, 100);
31
- return;
32
- }
33
- if (category && !consent.preferences[category]) {
34
- reject(new Error(`Consent not given for ${category} scripts`));
35
- return;
36
- }
37
- const s = document.createElement("script");
38
- s.id = id;
39
- s.src = src;
40
- s.async = true;
41
- for (const [k, v] of Object.entries(attrs)) s.setAttribute(k, v);
42
- s.onload = () => resolve();
43
- s.onerror = () => reject(new Error(`Failed to load script: ${src}`));
44
- document.body.appendChild(s);
45
- } catch {
46
- setTimeout(checkConsent, 100);
47
- }
48
- };
49
- checkConsent();
50
- });
51
- }
52
- function createDefaultConsentTheme() {
53
- return createTheme({
54
- palette: {
55
- primary: {
56
- main: "#1976d2",
57
- contrastText: "#ffffff"
58
- },
59
- secondary: {
60
- main: "#dc004e",
61
- contrastText: "#ffffff"
62
- },
63
- background: {
64
- default: "#fafafa",
65
- paper: "#ffffff"
66
- },
67
- text: {
68
- primary: "#333333",
69
- secondary: "#666666"
70
- },
71
- action: {
72
- hover: "rgba(25, 118, 210, 0.04)"
73
- }
74
- },
75
- typography: {
76
- fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
77
- body2: {
78
- fontSize: "0.875rem",
79
- lineHeight: 1.43
80
- },
81
- button: {
82
- fontWeight: 500,
83
- textTransform: "none"
84
- }
85
- },
86
- components: {
87
- MuiButton: {
88
- styleOverrides: {
89
- root: {
90
- borderRadius: 8,
91
- paddingX: 16,
92
- paddingY: 8
93
- },
94
- contained: {
95
- boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
96
- "&:hover": {
97
- boxShadow: "0 4px 8px rgba(0,0,0,0.15)"
98
- }
99
- }
100
- }
101
- },
102
- MuiPaper: {
103
- styleOverrides: {
104
- root: {
105
- borderRadius: 12
106
- }
107
- }
108
- },
109
- MuiDialog: {
110
- styleOverrides: {
111
- paper: {
112
- borderRadius: 16
113
- }
114
- }
115
- }
116
- }
117
- });
118
- }
119
- var defaultConsentTheme = () => createDefaultConsentTheme();
120
-
121
- // src/utils/autoConfigureCategories.ts
122
- var FORBIDDEN_NECESSARY_SCRIPTS = /* @__PURE__ */ new Set([
123
- // Analytics & Performance
124
- "google-analytics",
125
- "google-tag-manager",
126
- "hotjar",
127
- "mixpanel",
128
- "clarity",
129
- "amplitude",
130
- "segment",
131
- // Marketing & Advertising
132
- "facebook-pixel",
133
- "twitter-pixel",
134
- "linkedin-insight",
135
- "pinterest-tag",
136
- "snapchat-pixel",
137
- "tiktok-pixel",
138
- "reddit-pixel",
139
- // Communication & Support
140
- "intercom",
141
- "zendesk-chat",
142
- "drift",
143
- "crisp",
144
- "freshchat",
145
- // A/B Testing & Optimization
146
- "optimizely",
147
- "vwo",
148
- "google-optimize",
149
- "unbounce",
150
- // Social & Content
151
- "youtube-embed",
152
- "vimeo-embed",
153
- "twitter-widget",
154
- "facebook-widget",
155
- "instagram-widget",
156
- // Accessibility (exceto scripts críticos)
157
- "userway"
158
- ]);
159
- function analyzeIntegrationCategories(integrations) {
160
- const categoryMap = {};
161
- integrations.forEach((integration) => {
162
- const category = integration.category;
163
- if (!categoryMap[category]) {
164
- categoryMap[category] = [];
165
- }
166
- categoryMap[category].push(integration.id);
167
- });
168
- return categoryMap;
169
- }
170
- function autoConfigureCategories(originalConfig, integrations, options = {}) {
171
- const { warningOnly = false, silent = false } = options;
172
- const config = originalConfig || { enabledCategories: ["analytics"] };
173
- const categoryIntegrations = analyzeIntegrationCategories(integrations);
174
- const requiredCategories = Object.keys(categoryIntegrations);
175
- const currentCategories = new Set(config.enabledCategories || []);
176
- const missingCategories = requiredCategories.filter((cat) => !currentCategories.has(cat));
177
- let adjustedConfig = { ...config };
178
- let autoEnabledCategories = [];
179
- if (missingCategories.length > 0) {
180
- if (warningOnly) {
181
- if (!silent) {
182
- logMissingCategoriesWarning(missingCategories, categoryIntegrations);
183
- }
184
- } else {
185
- autoEnabledCategories = [...missingCategories];
186
- adjustedConfig = {
187
- ...config,
188
- enabledCategories: [...currentCategories, ...missingCategories]
189
- };
190
- if (!silent) {
191
- logAutoEnabledCategories(autoEnabledCategories, categoryIntegrations);
192
- }
193
- }
194
- }
195
- return {
196
- originalConfig: config,
197
- adjustedConfig,
198
- autoEnabledCategories,
199
- missingCategories,
200
- wasAdjusted: autoEnabledCategories.length > 0,
201
- categoryIntegrations
202
- };
203
- }
204
- function logMissingCategoriesWarning(missingCategories, categoryIntegrations) {
205
- const isDev = process.env.NODE_ENV !== "production";
206
- if (!isDev) return;
207
- const PREFIX = "[\u{1F36A} LGPD-CONSENT AUTO-CONFIG]";
208
- console.group(`${PREFIX} \u26A0\uFE0F Categorias Requeridas N\xE3o Habilitadas`);
209
- missingCategories.forEach((category) => {
210
- const integrations = categoryIntegrations[category] || [];
211
- console.warn(
212
- `${PREFIX} Categoria '${category}' requerida por integra\xE7\xF5es: ${integrations.join(", ")}`
213
- );
214
- });
215
- const categoriesCode = missingCategories.map((c) => `'${c}'`).join(", ");
216
- console.warn(
217
- `${PREFIX} Para corrigir, adicione estas categorias ao ConsentProvider:`,
218
- `categories={{ enabledCategories: [...existingCategories, ${categoriesCode}] }}`
219
- );
220
- console.groupEnd();
221
- }
222
- function logAutoEnabledCategories(autoEnabledCategories, categoryIntegrations) {
223
- const isDev = process.env.NODE_ENV !== "production";
224
- if (!isDev) return;
225
- const PREFIX = "[\u{1F36A} LGPD-CONSENT AUTO-CONFIG]";
226
- console.group(`${PREFIX} \u2705 Categorias Auto-Habilitadas`);
227
- autoEnabledCategories.forEach((category) => {
228
- const integrations = categoryIntegrations[category] || [];
229
- console.info(
230
- `${PREFIX} Categoria '${category}' auto-habilitada para integra\xE7\xF5es: ${integrations.join(", ")}`
231
- );
232
- });
233
- console.info(`${PREFIX} \u{1F4A1} Essas categorias foram automaticamente adicionadas \xE0 configura\xE7\xE3o.`);
234
- console.info(`${PREFIX} \u{1F527} Para controle manual, especifique explicitamente no ConsentProvider.`);
235
- console.groupEnd();
236
- }
237
- function validateIntegrationCategories(integrations, enabledCategories) {
238
- const requiredCategories = integrations.map((i) => i.category);
239
- const enabledSet = new Set(enabledCategories);
240
- return requiredCategories.every((category) => enabledSet.has(category));
241
- }
242
- function extractCategoriesFromIntegrations(integrations) {
243
- const categories = /* @__PURE__ */ new Set();
244
- integrations.forEach((integration) => {
245
- categories.add(integration.category);
246
- });
247
- return Array.from(categories);
248
- }
249
- function validateNecessaryClassification(integrations, enabledCategories) {
250
- const warnings = [];
251
- const hasNecessaryCategory = enabledCategories.includes("necessary");
252
- if (!hasNecessaryCategory) {
253
- return warnings;
254
- }
255
- const problematicIntegrations = integrations.filter(
256
- (integration) => integration.category === "necessary" && FORBIDDEN_NECESSARY_SCRIPTS.has(integration.id)
257
- );
258
- if (problematicIntegrations.length > 0) {
259
- warnings.push(
260
- `\u26A0\uFE0F ATEN\xC7\xC3O GDPR/LGPD: As seguintes integra\xE7\xF5es NUNCA devem ser classificadas como 'necessary':`
261
- );
262
- problematicIntegrations.forEach((integration) => {
263
- warnings.push(
264
- ` \u2022 '${integration.id}' (categoria: ${integration.category}) - Requer consentimento expl\xEDcito`
265
- );
266
- });
267
- warnings.push(
268
- `\u{1F4A1} Scripts 'necessary' executam SEM consentimento e podem resultar em multas.`,
269
- `\u{1F4DA} Apenas scripts de seguran\xE7a, autentica\xE7\xE3o ou core do site se qualificam.`,
270
- `\u{1F527} Mova estes scripts para categorias apropriadas (analytics, marketing, etc.)`
271
- );
272
- }
273
- return warnings;
274
- }
275
-
276
- // src/utils/ConsentScriptLoader.tsx
277
- function ConsentScriptLoader({
278
- integrations,
279
- reloadOnChange = false
280
- }) {
281
- const { preferences, consented } = useConsent();
282
- const categories = useCategories();
283
- const loadedScripts = React.useRef(/* @__PURE__ */ new Set());
284
- React.useEffect(() => {
285
- try {
286
- const ids = (integrations || []).map((i) => i.id);
287
- const gt = globalThis;
288
- const current = Array.isArray(gt.__LGPD_USED_INTEGRATIONS__) ? gt.__LGPD_USED_INTEGRATIONS__ : [];
289
- const merged = Array.from(/* @__PURE__ */ new Set([...current, ...ids]));
290
- gt.__LGPD_USED_INTEGRATIONS__ = merged;
291
- try {
292
- const gmap = globalThis;
293
- const map = gmap.__LGPD_INTEGRATIONS_MAP__ || {};
294
- (integrations || []).forEach((i) => {
295
- map[i.id] = i.category;
296
- });
297
- gmap.__LGPD_INTEGRATIONS_MAP__ = map;
298
- } catch {
299
- }
300
- } catch {
301
- }
302
- }, [integrations]);
303
- React.useEffect(() => {
304
- try {
305
- const required = Array.from(new Set((integrations || []).map((i) => i.category))).filter(
306
- Boolean
307
- );
308
- const gt = globalThis;
309
- const current = Array.isArray(gt.__LGPD_REQUIRED_CATEGORIES__) ? gt.__LGPD_REQUIRED_CATEGORIES__ : [];
310
- const merged = Array.from(/* @__PURE__ */ new Set([...current, ...required]));
311
- gt.__LGPD_REQUIRED_CATEGORIES__ = merged;
312
- if (typeof window !== "undefined" && typeof window.dispatchEvent === "function") {
313
- window.dispatchEvent(new CustomEvent("lgpd:requiredCategories"));
314
- }
315
- } catch {
316
- }
317
- }, [integrations]);
318
- React.useEffect(() => {
319
- const isDev = process.env.NODE_ENV !== "production";
320
- if (!isDev || integrations.length === 0) return;
321
- const enabledCategories = categories.allCategories.map((cat) => cat.id);
322
- const isValid = validateIntegrationCategories(integrations, enabledCategories);
323
- if (!isValid) {
324
- autoConfigureCategories({ enabledCategories }, integrations, {
325
- warningOnly: true,
326
- silent: false
327
- });
328
- }
329
- const necessaryWarnings = validateNecessaryClassification(integrations, enabledCategories);
330
- if (necessaryWarnings.length > 0) {
331
- console.group("\u{1F6A8} [LGPD-CONSENT] VALIDA\xC7\xC3O DE COMPLIANCE");
332
- necessaryWarnings.forEach((warning) => {
333
- if (warning.startsWith("\u26A0\uFE0F")) {
334
- console.error(warning);
335
- } else if (warning.startsWith("\u{1F4A1}") || warning.startsWith("\u{1F4DA}") || warning.startsWith("\u{1F527}")) {
336
- console.warn(warning);
337
- } else {
338
- console.log(warning);
339
- }
340
- });
341
- console.groupEnd();
342
- }
343
- }, [integrations, categories]);
344
- React.useEffect(() => {
345
- if (!consented) return;
346
- integrations.forEach(async (integration) => {
347
- const shouldLoad = preferences[integration.category];
348
- const alreadyLoaded = loadedScripts.current.has(integration.id);
349
- if (shouldLoad && (!alreadyLoaded || reloadOnChange)) {
350
- try {
351
- await loadScript(integration.id, integration.src, integration.category, integration.attrs);
352
- if (integration.init) {
353
- integration.init();
354
- }
355
- loadedScripts.current.add(integration.id);
356
- } catch (error) {
357
- logger.error(`\u274C Failed to load script: ${integration.id}`, error);
358
- }
359
- }
360
- });
361
- }, [preferences, consented, integrations, reloadOnChange]);
362
- return null;
363
- }
364
- function useConsentScriptLoader() {
365
- const { preferences, consented } = useConsent();
366
- return React.useCallback(
367
- async (integration) => {
368
- if (!consented) {
369
- logger.warn(`\u26A0\uFE0F Cannot load script ${integration.id}: No consent given`);
370
- return false;
371
- }
372
- const shouldLoad = preferences[integration.category];
373
- if (!shouldLoad) {
374
- logger.warn(
375
- `\u26A0\uFE0F Cannot load script ${integration.id}: Category '${integration.category}' not consented`
376
- );
377
- return false;
378
- }
379
- try {
380
- await loadScript(integration.id, integration.src, integration.category, integration.attrs);
381
- if (integration.init) {
382
- integration.init();
383
- }
384
- return true;
385
- } catch (error) {
386
- logger.error(`\u274C Failed to load script: ${integration.id}`, error);
387
- return false;
388
- }
389
- },
390
- [preferences, consented]
391
- );
392
- }
393
-
394
- // src/utils/scriptIntegrations.ts
395
- function createGoogleAnalyticsIntegration(config) {
396
- const src = config.scriptUrl ?? `https://www.googletagmanager.com/gtag/js?id=${config.measurementId}`;
397
- return {
398
- id: "google-analytics",
399
- category: "analytics",
400
- src,
401
- cookies: ["_ga", "_ga_*", "_gid"],
402
- cookiesInfo: [
403
- {
404
- name: "_ga",
405
- purpose: "Identifica\xE7\xE3o \xFAnica de visitantes para an\xE1lise de tr\xE1fego",
406
- duration: "2 anos",
407
- provider: "Google Analytics"
408
- },
409
- {
410
- name: "_ga_*",
411
- purpose: "Rastreamento de sess\xF5es e eventos espec\xEDficos do stream GA4",
412
- duration: "2 anos",
413
- provider: "Google Analytics"
414
- },
415
- {
416
- name: "_gid",
417
- purpose: "Distin\xE7\xE3o de visitantes \xFAnicos em per\xEDodo de 24h",
418
- duration: "24 horas",
419
- provider: "Google Analytics"
420
- }
421
- ],
422
- init: () => {
423
- if (typeof window !== "undefined") {
424
- const w = window;
425
- w.dataLayer = w.dataLayer ?? [];
426
- const gtag = (...args) => {
427
- w.dataLayer.push(...args);
428
- };
429
- w.gtag = gtag;
430
- gtag("js", /* @__PURE__ */ new Date());
431
- gtag("config", config.measurementId, config.config ?? {});
432
- }
433
- },
434
- attrs: { async: "true" }
435
- };
436
- }
437
- function createGoogleTagManagerIntegration(config) {
438
- const src = config.scriptUrl ?? `https://www.googletagmanager.com/gtm.js?id=${config.containerId}`;
439
- return {
440
- id: "google-tag-manager",
441
- category: "analytics",
442
- src,
443
- cookies: ["_gcl_au"],
444
- init: () => {
445
- if (typeof window !== "undefined") {
446
- const dataLayerName = config.dataLayerName || "dataLayer";
447
- const w = window;
448
- const layer = w[dataLayerName] ?? [];
449
- w[dataLayerName] = layer;
450
- layer.push({ "gtm.start": (/* @__PURE__ */ new Date()).getTime(), event: "gtm.js" });
451
- }
452
- }
453
- };
454
- }
455
- function createUserWayIntegration(config) {
456
- const src = config.scriptUrl ?? "https://cdn.userway.org/widget.js";
457
- return {
458
- id: "userway",
459
- category: "functional",
460
- src,
461
- cookies: ["_userway_*"],
462
- init: () => {
463
- if (typeof window !== "undefined") {
464
- const w = window;
465
- w.UserWayWidgetApp = w.UserWayWidgetApp || {};
466
- w.UserWayWidgetApp.accountId = config.accountId;
467
- }
468
- },
469
- attrs: { "data-account": config.accountId }
470
- };
471
- }
472
- var COMMON_INTEGRATIONS = {
473
- googleAnalytics: createGoogleAnalyticsIntegration,
474
- googleTagManager: createGoogleTagManagerIntegration,
475
- userway: createUserWayIntegration
476
- };
477
- function createFacebookPixelIntegration(config) {
478
- const src = config.scriptUrl ?? "https://connect.facebook.net/en_US/fbevents.js";
479
- return {
480
- id: "facebook-pixel",
481
- category: "marketing",
482
- src,
483
- cookies: ["_fbp", "fr"],
484
- init: () => {
485
- if (typeof window !== "undefined") {
486
- const w = window;
487
- if (!w.fbq) {
488
- const fbq = (...args) => {
489
- if (w.fbq && typeof w.fbq.callMethod === "function") {
490
- w.fbq.callMethod(...args);
491
- } else {
492
- fbq.queue = fbq.queue || [];
493
- fbq.queue.push(args);
494
- }
495
- };
496
- fbq.loaded = true;
497
- w.fbq = fbq;
498
- }
499
- w.fbq("init", config.pixelId, config.advancedMatching ?? {});
500
- if (config.autoTrack !== false) w.fbq("track", "PageView");
501
- }
502
- }
503
- };
504
- }
505
- function createHotjarIntegration(config) {
506
- const v = config.version ?? 6;
507
- const src = config.scriptUrl ?? `https://static.hotjar.com/c/hotjar-${config.siteId}.js?sv=${v}`;
508
- return {
509
- id: "hotjar",
510
- category: "analytics",
511
- src,
512
- cookies: [
513
- "_hjSession_*",
514
- "_hjSessionUser_*",
515
- "_hjFirstSeen",
516
- "_hjIncludedInSessionSample",
517
- "_hjAbsoluteSessionInProgress"
518
- ],
519
- cookiesInfo: [
520
- {
521
- name: "_hjSession_*",
522
- purpose: "Identifica\xE7\xE3o \xFAnica da sess\xE3o de grava\xE7\xE3o e heatmaps",
523
- duration: "30 minutos",
524
- provider: "Hotjar"
525
- },
526
- {
527
- name: "_hjSessionUser_*",
528
- purpose: "Identifica\xE7\xE3o persistente do usu\xE1rio entre sess\xF5es",
529
- duration: "365 dias",
530
- provider: "Hotjar"
531
- },
532
- {
533
- name: "_hjFirstSeen",
534
- purpose: "Detec\xE7\xE3o de primeira visita do usu\xE1rio ao site",
535
- duration: "Sess\xE3o",
536
- provider: "Hotjar"
537
- },
538
- {
539
- name: "_hjIncludedInSessionSample",
540
- purpose: "Indica se a sess\xE3o est\xE1 inclu\xEDda na amostra de grava\xE7\xE3o",
541
- duration: "30 minutos",
542
- provider: "Hotjar"
543
- },
544
- {
545
- name: "_hjAbsoluteSessionInProgress",
546
- purpose: "Detecta se uma sess\xE3o absoluta est\xE1 em progresso",
547
- duration: "30 minutos",
548
- provider: "Hotjar"
549
- }
550
- ],
551
- init: () => {
552
- if (typeof window !== "undefined") {
553
- const w = window;
554
- w._hjSettings = { hjid: config.siteId, hjsv: v };
555
- if (!w.hj) {
556
- const hj = (...args) => {
557
- hj.q = hj.q || [];
558
- hj.q.push(args);
559
- };
560
- w.hj = hj;
561
- }
562
- if (config.debug && typeof console !== "undefined" && typeof console.info === "function") {
563
- console.info("[Hotjar] initialized with siteId", config.siteId);
564
- }
565
- }
566
- }
567
- };
568
- }
569
- function createMixpanelIntegration(config) {
570
- const src = config.scriptUrl ?? "https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";
571
- return {
572
- id: "mixpanel",
573
- category: "analytics",
574
- src,
575
- cookies: ["mp_*"],
576
- cookiesInfo: [
577
- {
578
- name: "mp_*",
579
- purpose: "Rastreamento de eventos e propriedades do usu\xE1rio para analytics",
580
- duration: "1 ano",
581
- provider: "Mixpanel"
582
- }
583
- ],
584
- init: () => {
585
- if (typeof window !== "undefined") {
586
- const w = window;
587
- w.mixpanel = w.mixpanel || { init: () => void 0 };
588
- if (w.mixpanel && typeof w.mixpanel.init === "function") {
589
- try {
590
- w.mixpanel.init(config.token, config.config ?? {}, config.api_host);
591
- } catch (error) {
592
- if (typeof console !== "undefined" && typeof console.warn === "function") {
593
- console.warn("[Mixpanel] Failed to initialize:", error);
594
- }
595
- }
596
- }
597
- }
598
- }
599
- };
600
- }
601
- function createClarityIntegration(config) {
602
- const src = config.scriptUrl ?? `https://www.clarity.ms/tag/${config.projectId}`;
603
- return {
604
- id: "clarity",
605
- category: "analytics",
606
- src,
607
- cookies: ["_clck", "_clsk", "CLID", "ANONCHK", "MR", "MUID", "SM"],
608
- init: () => {
609
- if (typeof window !== "undefined" && typeof config.upload !== "undefined") {
610
- const w = window;
611
- if (typeof w.clarity === "function") {
612
- try {
613
- w.clarity("set", "upload", config.upload);
614
- } catch (error) {
615
- if (typeof console !== "undefined" && typeof console.warn === "function") {
616
- console.warn("[Clarity] Failed to configure upload setting:", error);
617
- }
618
- }
619
- }
620
- }
621
- }
622
- };
623
- }
624
- function createIntercomIntegration(config) {
625
- const src = config.scriptUrl ?? `https://widget.intercom.io/widget/${config.app_id}`;
626
- return {
627
- id: "intercom",
628
- category: "functional",
629
- src,
630
- cookies: ["intercom-id-*", "intercom-session-*"],
631
- init: () => {
632
- if (typeof window !== "undefined") {
633
- const w = window;
634
- if (typeof w.Intercom === "function") {
635
- try {
636
- w.Intercom("boot", { app_id: config.app_id });
637
- } catch (error) {
638
- if (typeof console !== "undefined" && typeof console.warn === "function") {
639
- console.warn("[Intercom] Failed to boot:", error);
640
- }
641
- }
642
- }
643
- }
644
- }
645
- };
646
- }
647
- function createZendeskChatIntegration(config) {
648
- const src = config.scriptUrl ?? `https://static.zdassets.com/ekr/snippet.js?key=${config.key}`;
649
- return {
650
- id: "zendesk-chat",
651
- category: "functional",
652
- src,
653
- cookies: ["__zlcmid", "_zendesk_shared_session"],
654
- init: () => {
655
- if (typeof window !== "undefined") {
656
- const w = window;
657
- if (typeof w.zE === "function") {
658
- try {
659
- w.zE("webWidget", "identify", { key: config.key });
660
- } catch (error) {
661
- if (typeof console !== "undefined" && typeof console.warn === "function") {
662
- console.warn("[Zendesk] Failed to identify:", error);
663
- }
664
- }
665
- }
666
- }
667
- }
668
- };
669
- }
670
- function createECommerceIntegrations(cfg) {
671
- const list = [];
672
- if (cfg.googleAnalytics) list.push(createGoogleAnalyticsIntegration(cfg.googleAnalytics));
673
- if (cfg.facebookPixel) list.push(createFacebookPixelIntegration(cfg.facebookPixel));
674
- if (cfg.hotjar) list.push(createHotjarIntegration(cfg.hotjar));
675
- if (cfg.userway) list.push(createUserWayIntegration(cfg.userway));
676
- return list;
677
- }
678
- function createSaaSIntegrations(cfg) {
679
- const list = [];
680
- if (cfg.googleAnalytics) list.push(createGoogleAnalyticsIntegration(cfg.googleAnalytics));
681
- if (cfg.mixpanel) list.push(createMixpanelIntegration(cfg.mixpanel));
682
- if (cfg.intercom) list.push(createIntercomIntegration(cfg.intercom));
683
- if (cfg.hotjar) list.push(createHotjarIntegration(cfg.hotjar));
684
- return list;
685
- }
686
- function createCorporateIntegrations(cfg) {
687
- const list = [];
688
- if (cfg.googleAnalytics) list.push(createGoogleAnalyticsIntegration(cfg.googleAnalytics));
689
- if (cfg.clarity) list.push(createClarityIntegration(cfg.clarity));
690
- if (cfg.zendesk) list.push(createZendeskChatIntegration(cfg.zendesk));
691
- if (cfg.userway) list.push(createUserWayIntegration(cfg.userway));
692
- return list;
693
- }
694
- var INTEGRATION_TEMPLATES = {
695
- ecommerce: {
696
- essential: ["google-analytics", "facebook-pixel"],
697
- optional: ["hotjar", "userway"],
698
- categories: ["analytics", "marketing", "functional"]
699
- },
700
- saas: {
701
- essential: ["google-analytics", "mixpanel"],
702
- optional: ["intercom", "hotjar"],
703
- categories: ["analytics", "functional"]
704
- },
705
- corporate: {
706
- essential: ["google-analytics"],
707
- optional: ["userway", "zendesk-chat", "clarity"],
708
- categories: ["analytics", "functional"]
709
- }
710
- };
711
- function suggestCategoryForScript(name) {
712
- const n = name.toLowerCase();
713
- if (n.includes("facebook") || n.includes("pixel") || n.includes("ads")) return ["marketing"];
714
- if (n.includes("hotjar") || n.includes("mixpanel") || n.includes("clarity")) return ["analytics"];
715
- if (n.includes("intercom") || n.includes("zendesk") || n.includes("chat")) return ["functional"];
716
- return ["analytics"];
717
- }
718
-
719
- // src/types/advancedTexts.ts
720
- var EXPANDED_DEFAULT_TEXTS = {
721
- // Textos adicionais
722
- confirm: "Confirmar",
723
- cancel: "Cancelar",
724
- loading: "Carregando...",
725
- // Feedback
726
- feedback: {
727
- saveSuccess: "Prefer\xEAncias salvas com sucesso!",
728
- saveError: "Erro ao salvar prefer\xEAncias. Tente novamente.",
729
- consentUpdated: "Consentimento atualizado.",
730
- cookiesRejected: "Cookies opcionais rejeitados.",
731
- settingsReset: "Configura\xE7\xF5es resetadas."
732
- },
733
- // Acessibilidade
734
- accessibility: {
735
- bannerLabel: "Banner de consentimento de cookies",
736
- modalLabel: "Modal de prefer\xEAncias de cookies",
737
- keyboardNavigation: "Use Tab para navegar, Enter para selecionar",
738
- toggleState: {
739
- enabled: "Habilitado",
740
- disabled: "Desabilitado"
741
- },
742
- liveRegion: "Regi\xE3o de an\xFAncios din\xE2micos"
743
- },
744
- // Categorias
745
- categories: {
746
- necessary: {
747
- name: "Cookies Necess\xE1rios",
748
- description: "Essenciais para o funcionamento b\xE1sico do site",
749
- examples: "Sess\xE3o, seguran\xE7a, prefer\xEAncias de idioma"
750
- },
751
- analytics: {
752
- name: "Cookies de Analytics",
753
- description: "Ajudam a entender como os visitantes usam o site",
754
- examples: "Google Analytics, contadores de p\xE1gina"
755
- },
756
- marketing: {
757
- name: "Cookies de Marketing",
758
- description: "Usados para personalizar an\xFAncios e ofertas",
759
- examples: "Facebook Pixel, Google Ads, remarketing"
760
- },
761
- functional: {
762
- name: "Cookies Funcionais",
763
- description: "Melhoram a funcionalidade e personaliza\xE7\xE3o",
764
- examples: "Chat, mapas, v\xEDdeos embarcados"
765
- },
766
- performance: {
767
- name: "Cookies de Performance",
768
- description: "Coletam informa\xE7\xF5es sobre velocidade e estabilidade",
769
- examples: "Monitoramento de erro, otimiza\xE7\xE3o de velocidade"
770
- }
771
- },
772
- // Contextos específicos
773
- contexts: {
774
- ecommerce: {
775
- cartAbandonment: "Lembramos dos produtos no seu carrinho",
776
- personalizedOffers: "Ofertas personalizadas baseadas no seu hist\xF3rico",
777
- paymentSecurity: "Seguran\xE7a adicional no processo de pagamento",
778
- productRecommendations: "Sugest\xF5es de produtos relevantes"
779
- },
780
- saas: {
781
- userAnalytics: "An\xE1lise de uso para melhorar funcionalidades",
782
- performanceMonitoring: "Monitoramento de performance da aplica\xE7\xE3o",
783
- featureUsage: "Estat\xEDsticas de uso de recursos",
784
- customerSupport: "Suporte ao cliente mais eficiente"
785
- },
786
- government: {
787
- citizenServices: "Melhoria dos servi\xE7os ao cidad\xE3o",
788
- dataProtection: "Prote\xE7\xE3o rigorosa dos dados pessoais",
789
- transparency: "Transpar\xEAncia no uso de dados",
790
- accessibility: "Recursos de acessibilidade digital"
791
- },
792
- education: {
793
- studentProgress: "Acompanhamento do progresso educacional",
794
- learningAnalytics: "Analytics para melhorar o aprendizado",
795
- accessibility: "Recursos educacionais acess\xEDveis",
796
- parentalConsent: "Consentimento parental quando necess\xE1rio"
797
- }
798
- },
799
- // Variações de tom
800
- variants: {
801
- formal: {
802
- bannerMessage: "Este s\xEDtio eletr\xF4nico utiliza cookies para otimizar a experi\xEAncia de navega\xE7\xE3o.",
803
- acceptAll: "Concordar com todos os cookies",
804
- declineAll: "Recusar cookies opcionais",
805
- modalTitle: "Configura\xE7\xE3o de Cookies"
806
- },
807
- casual: {
808
- bannerMessage: "\u{1F36A} Ei! Usamos cookies para tornar sua experi\xEAncia ainda melhor!",
809
- acceptAll: "Aceitar tudo",
810
- declineAll: "S\xF3 o essencial",
811
- modalTitle: "Seus Cookies"
812
- },
813
- concise: {
814
- bannerMessage: "Usamos cookies. Voc\xEA aceita?",
815
- acceptAll: "Sim",
816
- declineAll: "N\xE3o",
817
- modalTitle: "Cookies"
818
- },
819
- detailed: {
820
- bannerMessage: "Utilizamos cookies e tecnologias similares para melhorar sua experi\xEAncia de navega\xE7\xE3o, personalizar conte\xFAdo, analisar tr\xE1fego e oferecer funcionalidades de redes sociais.",
821
- acceptAll: "Aceitar todos os cookies e tecnologias",
822
- declineAll: "Recusar todos os cookies opcionais",
823
- modalTitle: "Centro de Prefer\xEAncias de Privacidade"
824
- }
825
- },
826
- // Internacionalização simplificada (apenas textos básicos)
827
- i18n: {
828
- en: {
829
- bannerMessage: "We use cookies to enhance your experience.",
830
- acceptAll: "Accept All",
831
- declineAll: "Decline",
832
- preferences: "Preferences",
833
- modalTitle: "Cookie Preferences",
834
- modalIntro: "Customize your cookie preferences below.",
835
- save: "Save Preferences",
836
- necessaryAlwaysOn: "Necessary cookies (always active)"
837
- },
838
- es: {
839
- bannerMessage: "Utilizamos cookies para mejorar su experiencia.",
840
- acceptAll: "Aceptar Todo",
841
- declineAll: "Rechazar",
842
- preferences: "Preferencias",
843
- modalTitle: "Preferencias de Cookies",
844
- modalIntro: "Personalice sus preferencias de cookies a continuaci\xF3n.",
845
- save: "Guardar Preferencias",
846
- necessaryAlwaysOn: "Cookies necess\xE1rias (sempre ativas)"
847
- },
848
- fr: {
849
- bannerMessage: "Nous utilisons des cookies pour am\xE9liorer votre exp\xE9rience.",
850
- acceptAll: "Tout Accepter",
851
- declineAll: "Refuser",
852
- preferences: "Pr\xE9f\xE9rences",
853
- modalTitle: "Pr\xE9f\xE9rences des Cookies",
854
- modalIntro: "Personnalisez vos pr\xE9f\xE9rences de cookies ci-dessous.",
855
- save: "Enregistrer les Pr\xE9f\xE9rences",
856
- necessaryAlwaysOn: "Cookies n\xE9cessaires (toujours actifs)"
857
- }
858
- },
859
- // Textos técnicos
860
- technical: {
861
- sessionCookies: "Cookies de sess\xE3o s\xE3o tempor\xE1rios e expiram quando voc\xEA fecha o navegador.",
862
- persistentCookies: "Cookies persistentes permanecem no seu dispositivo at\xE9 expirarem ou serem removidos.",
863
- thirdPartyCookies: "Cookies de terceiros s\xE3o definidos por dom\xEDnios diferentes do site que voc\xEA est\xE1 visitando.",
864
- browserSettings: "Voc\xEA pode gerenciar cookies nas configura\xE7\xF5es do seu navegador.",
865
- disablingImpact: "Desabilitar cookies pode afetar a funcionalidade do site."
866
- },
867
- // Cookie details
868
- cookieDetails: {
869
- tableHeaders: {
870
- name: "Nome",
871
- purpose: "Finalidade",
872
- duration: "Dura\xE7\xE3o",
873
- provider: "Fornecedor",
874
- type: "Tipo"
875
- },
876
- noCookies: "Nenhum cookie encontrado para esta categoria.",
877
- toggleDetails: {
878
- expand: "Ver detalhes",
879
- collapse: "Ocultar detalhes"
880
- }
881
- }
882
- };
883
- function resolveTexts(texts, options = {}) {
884
- const { language = "pt", variant } = options;
885
- let resolved = { ...texts };
886
- if (variant && texts.variants?.[variant]) {
887
- resolved = { ...resolved, ...texts.variants[variant] };
888
- }
889
- if (language !== "pt" && texts.i18n?.[language]) {
890
- resolved = { ...resolved, ...texts.i18n[language] };
891
- }
892
- return resolved;
893
- }
894
- var TEXT_TEMPLATES = {
895
- ecommerce: {
896
- ...EXPANDED_DEFAULT_TEXTS,
897
- bannerMessage: "Utilizamos cookies para personalizar ofertas e melhorar sua experi\xEAncia de compra.",
898
- acceptAll: "Aceitar e continuar",
899
- variants: {
900
- casual: {
901
- bannerMessage: "\u{1F6D2} Usamos cookies para encontrar as melhores ofertas para voc\xEA!",
902
- acceptAll: "Quero ofertas personalizadas!"
903
- }
904
- }
905
- },
906
- saas: {
907
- ...EXPANDED_DEFAULT_TEXTS,
908
- bannerMessage: "Utilizamos cookies para otimizar o desempenho da aplica\xE7\xE3o e sua experi\xEAncia.",
909
- acceptAll: "Aceitar e otimizar",
910
- variants: {
911
- formal: {
912
- bannerMessage: "Esta aplica\xE7\xE3o utiliza cookies para an\xE1lise de performance e melhoria cont\xEDnua da experi\xEAncia do usu\xE1rio.",
913
- acceptAll: "Autorizar coleta de dados de uso"
914
- }
915
- }
916
- },
917
- government: {
918
- ...EXPANDED_DEFAULT_TEXTS,
919
- bannerMessage: "Este portal utiliza cookies em conformidade com a LGPD para melhorar os servi\xE7os p\xFAblicos.",
920
- acceptAll: "Aceitar em conformidade",
921
- variants: {
922
- formal: {
923
- bannerMessage: "Este s\xEDtio eletr\xF4nico do governo utiliza cookies estritamente necess\xE1rios e opcionais, em conformidade com a Lei Geral de Prote\xE7\xE3o de Dados.",
924
- acceptAll: "Concordar com o uso de cookies"
925
- }
926
- }
927
- }
928
- };
929
-
930
- export { COMMON_INTEGRATIONS, ConsentGate, ConsentScriptLoader, EXPANDED_DEFAULT_TEXTS, INTEGRATION_TEMPLATES, TEXT_TEMPLATES, analyzeIntegrationCategories, autoConfigureCategories, createClarityIntegration, createCorporateIntegrations, createDefaultConsentTheme, createECommerceIntegrations, createFacebookPixelIntegration, createGoogleAnalyticsIntegration, createGoogleTagManagerIntegration, createHotjarIntegration, createIntercomIntegration, createMixpanelIntegration, createSaaSIntegrations, createUserWayIntegration, createZendeskChatIntegration, defaultConsentTheme, extractCategoriesFromIntegrations, loadScript, resolveTexts, suggestCategoryForScript, useConsentScriptLoader, validateIntegrationCategories, validateNecessaryClassification };
1
+ export * from '@react-lgpd-consent/mui';