@luwiostack/cookie-consent 0.0.0-stage → 0.1.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.mjs ADDED
@@ -0,0 +1,558 @@
1
+ import { i as isConsentCategoryId, n as CONSENT_CATEGORIES, r as REQUIRED_CATEGORY, t as ConsentError } from "./errors-D2ZIcEYK.mjs";
2
+ import { t as usedVendors } from "./used-vendors-Dxk4PZtY.mjs";
3
+ import { localStore } from "@luwiostack/storage";
4
+ //#region src/domain/consent-decision.ts
5
+ /**
6
+ * One visitor's answer to the consent question: which categories they granted, under which policy
7
+ * version, and when. Immutable and always valid — the factory throws on a malformed input.
8
+ *
9
+ * Validity over time (policy version, expiry) is not the decision's concern: the consent instance
10
+ * decides whether a stored decision still counts.
11
+ */
12
+ var ConsentDecision = class ConsentDecision {
13
+ consent_id;
14
+ policy_version;
15
+ /** When the decision was made, in epoch milliseconds. */
16
+ decided_at;
17
+ #granted;
18
+ constructor(input) {
19
+ this.consent_id = input.consent_id;
20
+ this.policy_version = input.policy_version;
21
+ this.decided_at = input.decided_at;
22
+ this.#granted = new Set(input.granted);
23
+ }
24
+ /** @throws {ConsentError} on an empty `consent_id` / `policy_version` or a non-finite `decided_at`. */
25
+ static new(input) {
26
+ if (typeof input.consent_id !== "string" || input.consent_id === "") throw new ConsentError("A consent decision needs a non-empty consent_id.");
27
+ if (typeof input.policy_version !== "string" || input.policy_version === "") throw new ConsentError("A consent decision needs a non-empty policy_version.");
28
+ if (typeof input.decided_at !== "number" || !Number.isFinite(input.decided_at)) throw new ConsentError("A consent decision needs decided_at as finite epoch milliseconds.");
29
+ return new ConsentDecision(input);
30
+ }
31
+ /** Like {@link ConsentDecision.new}, but returns `null` instead of throwing. */
32
+ static tryNew(input) {
33
+ try {
34
+ return ConsentDecision.new(input);
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+ /** Whether this decision grants the category. */
40
+ isGranted(id) {
41
+ return this.#granted.has(id);
42
+ }
43
+ /** Every granted category id. */
44
+ granted() {
45
+ return [...this.#granted];
46
+ }
47
+ /** Same id, version, time and granted set. */
48
+ equals(other) {
49
+ if (this.consent_id !== other.consent_id || this.policy_version !== other.policy_version || this.decided_at !== other.decided_at || this.#granted.size !== other.#granted.size) return false;
50
+ for (const id of this.#granted) if (!other.#granted.has(id)) return false;
51
+ return true;
52
+ }
53
+ /** The serialized form kept in the store. */
54
+ toJSON() {
55
+ return {
56
+ consent_id: this.consent_id,
57
+ policy_version: this.policy_version,
58
+ granted: this.granted(),
59
+ decided_at: this.decided_at
60
+ };
61
+ }
62
+ };
63
+ //#endregion
64
+ //#region src/consent.ts
65
+ /** The key the default `localStorage` store keeps the decision behind. */
66
+ const DEFAULT_STORAGE_KEY = "luwio.consent";
67
+ /** The default decision lifetime: 365 days. */
68
+ const DEFAULT_MAX_AGE = 31536e6;
69
+ const PENDING = Object.freeze({
70
+ status: "pending",
71
+ decision: null
72
+ });
73
+ const COOKIE_TYPES = /* @__PURE__ */ new Set([
74
+ "http",
75
+ "local_storage",
76
+ "session_storage",
77
+ "indexed_db",
78
+ "pixel"
79
+ ]);
80
+ /** Checks one vendor declaration: an id, unique cookie names, valid categories and lifetimes. */
81
+ function validateVendor(vendor, listedIn) {
82
+ if (typeof vendor?.id !== "string" || vendor.id === "") throw new ConsentError(`Category "${listedIn}": a vendor id must be non-empty.`);
83
+ const where = `Vendor "${vendor.id}"`;
84
+ if (!Array.isArray(vendor.cookies)) throw new ConsentError(`${where}: cookies must be an array.`);
85
+ const names = /* @__PURE__ */ new Set();
86
+ for (const cookie of vendor.cookies) {
87
+ if (typeof cookie.name !== "string" || cookie.name === "") throw new ConsentError(`${where}: a cookie name must be non-empty.`);
88
+ if (names.has(cookie.name)) throw new ConsentError(`${where}: duplicate cookie "${cookie.name}".`);
89
+ names.add(cookie.name);
90
+ if (!isConsentCategoryId(cookie.category)) throw new ConsentError(`${where}: cookie "${cookie.name}" needs a category (${CONSENT_CATEGORIES.join(", ")}).`);
91
+ if (cookie.type !== void 0 && !COOKIE_TYPES.has(cookie.type)) throw new ConsentError(`${where}: cookie "${cookie.name}" has an unknown type "${cookie.type}".`);
92
+ const { max_age } = cookie;
93
+ if (!(max_age === "session" || max_age === "persistent" || typeof max_age === "number" && Number.isFinite(max_age) && max_age > 0)) throw new ConsentError(`${where}: cookie "${cookie.name}" needs max_age as positive milliseconds, 'session' or 'persistent'.`);
94
+ }
95
+ }
96
+ /**
97
+ * Resolves the per-category config into the vendors the app actually uses: a vendor listed under a
98
+ * category brings its cookies of that category, plus its necessary cookies (always allowed, and part
99
+ * of any use of the service). A vendor listed under several categories is merged into one.
100
+ */
101
+ function resolveVendors(config) {
102
+ if (typeof config !== "object" || config === null || Array.isArray(config)) throw new ConsentError("categories must be an object of category id → vendors.");
103
+ for (const key of Object.keys(config)) if (!isConsentCategoryId(key)) throw new ConsentError(`Unknown consent category "${key}" — use ${CONSENT_CATEGORIES.join(", ")}.`);
104
+ const merged = /* @__PURE__ */ new Map();
105
+ const listed = Object.fromEntries(CONSENT_CATEGORIES.map((id) => [id, []]));
106
+ for (const category of CONSENT_CATEGORIES) {
107
+ const inCategory = config[category];
108
+ if (inCategory === void 0) continue;
109
+ if (!Array.isArray(inCategory)) throw new ConsentError(`Category "${category}": vendors must be an array.`);
110
+ const seen = /* @__PURE__ */ new Set();
111
+ for (const vendor of inCategory) {
112
+ validateVendor(vendor, category);
113
+ const where = `Category "${category}", vendor "${vendor.id}"`;
114
+ if (seen.has(vendor.id)) throw new ConsentError(`${where}: duplicate vendor.`);
115
+ seen.add(vendor.id);
116
+ listed[category].push(vendor.id);
117
+ if (vendor.cookies.filter((c) => c.category === category).length === 0) throw new ConsentError(`${where}: the vendor has no ${category} cookies.`);
118
+ const entry = merged.get(vendor.id) ?? {
119
+ vendor,
120
+ cookies: /* @__PURE__ */ new Map()
121
+ };
122
+ for (const cookie of vendor.cookies) if (cookie.category === category || cookie.category === "necessary") entry.cookies.set(cookie.name, cookie);
123
+ merged.set(vendor.id, entry);
124
+ }
125
+ }
126
+ return {
127
+ vendors: [...merged.values()].map(({ vendor, cookies }) => ({
128
+ ...vendor,
129
+ cookies: vendor.cookies.filter((c) => cookies.has(c.name))
130
+ })),
131
+ listed
132
+ };
133
+ }
134
+ function reusableId(record) {
135
+ const id = record?.consent_id;
136
+ return typeof id === "string" && id !== "" ? id : null;
137
+ }
138
+ function randomId() {
139
+ const c = globalThis.crypto;
140
+ if (c && typeof c.randomUUID === "function") return c.randomUUID();
141
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
142
+ }
143
+ /**
144
+ * Create a consent instance: per category, the vendors the app uses there (a vendor brings only its
145
+ * cookies of that category, plus its necessary ones), where the decision is kept, and when it must
146
+ * be asked again. Create it once (module
147
+ * scope is fine — storage is only touched on access, so it's SSR-safe) and hand it to
148
+ * `<Consent consent={…}>` in React, or use it directly.
149
+ *
150
+ * ```ts
151
+ * import { googleAnalytics, youtube } from '@luwiostack/cookie-consent/vendors'
152
+ *
153
+ * const consent = createConsent({
154
+ * categories: {
155
+ * statistics: [googleAnalytics()],
156
+ * preferences: [youtube()], // the embed only — no YouTube tracking cookies
157
+ * },
158
+ * policyVersion: 2,
159
+ * })
160
+ * consent.isGranted('preferences', 'youtube') // the embed may load
161
+ * consent.isGranted('marketing', 'youtube') // false — not used there
162
+ * ```
163
+ *
164
+ * @throws {ConsentError} for an invalid `maxAge`, an unknown category, or an invalid vendor (listed
165
+ * twice in a category, no cookies of the category it's listed in, duplicate cookie, empty name,
166
+ * missing cookie category, bad `max_age` / `type`).
167
+ */
168
+ function createConsent(config = {}) {
169
+ const { vendors, listed } = resolveVendors(config.categories ?? {});
170
+ const byId = new Map(vendors.map((v) => [v.id, v]));
171
+ const categories = CONSENT_CATEGORIES.map((id) => {
172
+ const ids = [.../* @__PURE__ */ new Set([...listed[id], ...vendors.map((v) => v.id)])];
173
+ return {
174
+ id,
175
+ required: id === REQUIRED_CATEGORY,
176
+ vendors: ids.flatMap((vendorId) => {
177
+ const vendor = byId.get(vendorId);
178
+ const cookies = vendor.cookies.filter((c) => c.category === id);
179
+ return cookies.length > 0 ? [{
180
+ ...vendor,
181
+ cookies
182
+ }] : [];
183
+ })
184
+ };
185
+ });
186
+ const usedIn = usedVendors(categories);
187
+ const maxAge = config.maxAge ?? 31536e6;
188
+ if (typeof maxAge !== "number" || Number.isNaN(maxAge) || maxAge <= 0) throw new ConsentError("maxAge must be a positive number of milliseconds.");
189
+ const policyVersion = String(config.policyVersion ?? 1);
190
+ const store = config.store ?? localStore("luwio.consent", { onError: "ignore" });
191
+ const now = config.now ?? Date.now;
192
+ let unsaved;
193
+ const listeners = /* @__PURE__ */ new Set();
194
+ const notify = () => {
195
+ for (const fn of [...listeners]) fn();
196
+ };
197
+ const read = () => unsaved !== void 0 ? unsaved : store.read();
198
+ let lastRecord;
199
+ let lastExpired = false;
200
+ let lastSnapshot = PENDING;
201
+ function toDecision(record) {
202
+ if (record.policy_version !== policyVersion) return null;
203
+ if (!Array.isArray(record.granted)) return null;
204
+ const granted = /* @__PURE__ */ new Set([REQUIRED_CATEGORY]);
205
+ for (const id of record.granted) if (isConsentCategoryId(id)) granted.add(id);
206
+ return ConsentDecision.tryNew({
207
+ ...record,
208
+ granted
209
+ });
210
+ }
211
+ function getSnapshot() {
212
+ const record = read();
213
+ const age = record === null ? 0 : now() - record.decided_at;
214
+ const expired = record !== null && (age > maxAge || age < -3e5);
215
+ if (record === lastRecord && expired === lastExpired) return lastSnapshot;
216
+ lastRecord = record;
217
+ lastExpired = expired;
218
+ const decision = record && !expired ? toDecision(record) : null;
219
+ lastSnapshot = decision ? Object.freeze({
220
+ status: "decided",
221
+ decision
222
+ }) : PENDING;
223
+ return lastSnapshot;
224
+ }
225
+ function current() {
226
+ return getSnapshot().decision;
227
+ }
228
+ function commit(granted) {
229
+ const previous = current();
230
+ const set = /* @__PURE__ */ new Set([REQUIRED_CATEGORY]);
231
+ for (const id of granted) if (isConsentCategoryId(id)) set.add(id);
232
+ const next = ConsentDecision.new({
233
+ consent_id: previous?.consent_id ?? reusableId(read()) ?? randomId(),
234
+ policy_version: policyVersion,
235
+ granted: CONSENT_CATEGORIES.filter((id) => set.has(id)),
236
+ decided_at: now()
237
+ });
238
+ const record = next.toJSON();
239
+ store.write(record);
240
+ const kept = store.read();
241
+ const landed = kept?.consent_id === record.consent_id && kept?.decided_at === record.decided_at;
242
+ unsaved = landed ? void 0 : record;
243
+ if (!landed) notify();
244
+ config.onChange?.(next, previous);
245
+ return next;
246
+ }
247
+ const isRequired = (id) => id === REQUIRED_CATEGORY;
248
+ const isGranted = (id, vendorId) => (vendorId === void 0 || usedIn[id].has(vendorId)) && (isRequired(id) || (current()?.isGranted(id) ?? false));
249
+ return {
250
+ categories,
251
+ vendors,
252
+ policyVersion,
253
+ getSnapshot,
254
+ subscribe: (onChange) => {
255
+ listeners.add(onChange);
256
+ const unsubscribe = store.subscribe(onChange);
257
+ return () => {
258
+ listeners.delete(onChange);
259
+ unsubscribe();
260
+ };
261
+ },
262
+ isGranted,
263
+ isRequired,
264
+ acceptAll: () => commit(CONSENT_CATEGORIES),
265
+ rejectAll: () => commit([]),
266
+ save: (granted) => commit(granted),
267
+ grant: (...grant) => commit([...current()?.granted() ?? [], ...grant]),
268
+ revoke: (...revoke) => {
269
+ const drop = new Set(revoke);
270
+ return commit((current()?.granted() ?? []).filter((id) => !drop.has(id)));
271
+ },
272
+ reset: () => {
273
+ const previous = current();
274
+ store.clear();
275
+ if (unsaved !== void 0) {
276
+ unsaved = void 0;
277
+ notify();
278
+ }
279
+ config.onChange?.(null, previous);
280
+ }
281
+ };
282
+ }
283
+ //#endregion
284
+ //#region src/formatters/consent-cookie-formatter.ts
285
+ const SECOND = 1e3;
286
+ const MINUTE = 60 * SECOND;
287
+ const HOUR = 60 * MINUTE;
288
+ const DAY = 24 * HOUR;
289
+ const UNITS = [
290
+ ["year", 365 * DAY],
291
+ ["month", 30 * DAY],
292
+ ["day", DAY],
293
+ ["hour", HOUR],
294
+ ["minute", MINUTE],
295
+ ["second", SECOND]
296
+ ];
297
+ /** Renders a cookie declaration's values for people. */
298
+ var ConsentCookieFormatter = class {
299
+ /**
300
+ * A cookie's lifetime in `locale`, in the largest unit that divides it evenly: 2 years, 3 months,
301
+ * 400 days, 30 minutes — falling back to whole days (or the largest unit that fits) when nothing
302
+ * divides evenly. Returns `null` for `'session'` and `'persistent'`: those are words, so render
303
+ * them through your own translations.
304
+ */
305
+ static formatLocale(cookie, locale, options = {}) {
306
+ const { max_age } = cookie;
307
+ if (typeof max_age !== "number") return null;
308
+ const unitDisplay = options.unitDisplay ?? "long";
309
+ const [unit, ms] = UNITS.find(([, ms]) => max_age >= ms && max_age % ms === 0) ?? (max_age >= DAY ? UNITS[2] : UNITS.find(([, u]) => max_age >= u) ?? UNITS[5]);
310
+ const value = Math.max(1, Math.round(max_age / ms));
311
+ return new Intl.NumberFormat(locale.toString(), {
312
+ style: "unit",
313
+ unit,
314
+ unitDisplay
315
+ }).format(value);
316
+ }
317
+ };
318
+ //#endregion
319
+ //#region src/integrations/clear-revoked-cookies.ts
320
+ /** A declared name as a matcher: `*` matches any run of characters (`_ga_*`, `ttcsid*`). */
321
+ function matcher(name) {
322
+ if (!name.includes("*")) return (actual) => actual === name;
323
+ const pattern = name.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"));
324
+ const re = new RegExp(`^${pattern.join(".*")}$`);
325
+ return (actual) => re.test(actual);
326
+ }
327
+ /**
328
+ * The domains a first-party cookie may have been set for: none (host-only), the host itself, and
329
+ * each parent domain (`www.shop.example.com` → `shop.example.com`, `example.com`). Analytics tags
330
+ * usually set theirs on the registrable domain, so deleting needs the same `Domain` attribute.
331
+ * A bare top-level domain (`com`) is never a valid cookie domain, so it's left out.
332
+ * @internal
333
+ */
334
+ function domainCandidates(hostname) {
335
+ const parts = hostname.split(".");
336
+ const parents = [];
337
+ for (let i = 0; i < parts.length - 1; i++) parents.push(parts.slice(i).join("."));
338
+ return [void 0, ...parents];
339
+ }
340
+ /** The paths a cookie may have been set for, from this page up to the root: `/a/b` → `/a/b`, `/a`, `/`. @internal */
341
+ function pathCandidates(pathname) {
342
+ const segments = pathname.split("/").filter(Boolean);
343
+ const paths = ["/"];
344
+ for (let i = 1; i <= segments.length; i++) paths.push(`/${segments.slice(0, i).join("/")}`);
345
+ return paths;
346
+ }
347
+ function cookieNames(doc) {
348
+ return doc.cookie.split(";").map((pair) => pair.slice(0, pair.indexOf("=") === -1 ? void 0 : pair.indexOf("=")).trim()).filter(Boolean);
349
+ }
350
+ function expireCookie(doc, name) {
351
+ const { hostname, pathname } = doc.location;
352
+ for (const domain of domainCandidates(hostname)) for (const path of pathCandidates(pathname)) doc.cookie = `${name}=; Path=${path}${domain ? `; Domain=${domain}` : ""}; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`;
353
+ }
354
+ function storageKeys(storage) {
355
+ const keys = [];
356
+ for (let i = 0; i < storage.length; i++) {
357
+ const key = storage.key(i);
358
+ if (key !== null) keys.push(key);
359
+ }
360
+ return keys;
361
+ }
362
+ /**
363
+ * Remove what a withdrawn category left behind. At start and on every change, the declared cookies
364
+ * and storage items of every category that isn't granted are deleted — after "withdraw statistics",
365
+ * `_ga` and `_ga_*` are gone, not just unused. `necessary` is never touched, and a name a granted
366
+ * category also declares is kept.
367
+ *
368
+ * Only **first-party** storage can be reached: cookies on your own domain (tried with every parent
369
+ * domain and path, since tags set them broadly), `localStorage` / `sessionStorage` items and
370
+ * IndexedDB databases. A third-party cookie (`IDE` on doubleclick.net) lives on another site and
371
+ * can't be removed from yours; `HttpOnly` cookies only by your server. Scripts already running keep
372
+ * running — reload the page (e.g. from `onClear`) to stop them.
373
+ *
374
+ * Returns a stop function. A no-op on the server.
375
+ */
376
+ function clearRevokedCookies(consent, options = {}) {
377
+ if (typeof document === "undefined") return () => {};
378
+ const clear = () => {
379
+ const kept = [];
380
+ const revoked = [];
381
+ for (const category of consent.categories) {
382
+ const granted = category.id === "necessary" || consent.isGranted(category.id);
383
+ for (const vendor of category.vendors) for (const cookie of vendor.cookies) if (granted) kept.push(matcher(cookie.name));
384
+ else revoked.push(cookie);
385
+ }
386
+ if (revoked.length === 0) return;
387
+ const isKept = (actual) => kept.some((matches) => matches(actual));
388
+ const cleared = (cookie, actual) => options.onClear?.(cookie, actual);
389
+ for (const cookie of revoked) {
390
+ const matches = matcher(cookie.name);
391
+ const type = cookie.type ?? "http";
392
+ if (type === "http") for (const actual of cookieNames(document)) {
393
+ if (!matches(actual) || isKept(actual)) continue;
394
+ expireCookie(document, actual);
395
+ if (!cookieNames(document).includes(actual)) cleared(cookie, actual);
396
+ }
397
+ else if (type === "local_storage" || type === "session_storage") {
398
+ let storage;
399
+ try {
400
+ storage = type === "local_storage" ? window.localStorage : window.sessionStorage;
401
+ } catch {
402
+ continue;
403
+ }
404
+ for (const actual of storageKeys(storage)) {
405
+ if (!matches(actual) || isKept(actual)) continue;
406
+ storage.removeItem(actual);
407
+ cleared(cookie, actual);
408
+ }
409
+ } else if (type === "indexed_db" && typeof indexedDB !== "undefined") {
410
+ if (typeof indexedDB.databases === "function") indexedDB.databases().then((databases) => {
411
+ for (const { name } of databases) {
412
+ if (!name || !matches(name) || isKept(name)) continue;
413
+ indexedDB.deleteDatabase(name);
414
+ cleared(cookie, name);
415
+ }
416
+ });
417
+ else if (!cookie.name.includes("*") && !isKept(cookie.name)) indexedDB.deleteDatabase(cookie.name);
418
+ }
419
+ }
420
+ };
421
+ clear();
422
+ return consent.subscribe(clear);
423
+ }
424
+ //#endregion
425
+ //#region src/integrations/google-consent-mode.ts
426
+ /** The standard mapping of Google's signals onto the fixed categories — the default. */
427
+ const DEFAULT_GOOGLE_CONSENT_MAPPING = {
428
+ ad_storage: "marketing",
429
+ ad_user_data: "marketing",
430
+ ad_personalization: "marketing",
431
+ analytics_storage: "statistics",
432
+ functionality_storage: "preferences",
433
+ personalization_storage: "preferences",
434
+ security_storage: "necessary"
435
+ };
436
+ function resolveGtag() {
437
+ if (typeof window === "undefined") return void 0;
438
+ const w = window;
439
+ if (typeof w.gtag === "function") return w.gtag;
440
+ w.dataLayer = w.dataLayer ?? [];
441
+ const dataLayer = w.dataLayer;
442
+ w.gtag = function gtag() {
443
+ dataLayer.push(arguments);
444
+ };
445
+ return w.gtag;
446
+ }
447
+ /**
448
+ * Wire a consent instance to Google Consent Mode v2: sends `gtag('consent', 'default', …)` with every
449
+ * mapped signal denied (signals mapped to required categories granted), then an `update` with the
450
+ * visitor's decision — immediately when one is stored, and again on every change.
451
+ *
452
+ * Call it **before** the Google tag (gtag.js / GTM) loads, so the default is in place for its first
453
+ * hit. Returns an unsubscribe. A no-op on the server.
454
+ */
455
+ function googleConsentMode(consent, options = {}) {
456
+ const gtag = options.gtag ?? resolveGtag();
457
+ if (!gtag) return () => {};
458
+ const entries = Object.entries(options.mapping ?? DEFAULT_GOOGLE_CONSENT_MAPPING);
459
+ const signals = (isGranted) => {
460
+ const out = {};
461
+ for (const [signal, cat] of entries) out[signal] = (typeof cat === "string" ? [cat] : cat).every(isGranted) ? "granted" : "denied";
462
+ return out;
463
+ };
464
+ if (options.adsDataRedaction) gtag("set", "ads_data_redaction", true);
465
+ if (options.urlPassthrough) gtag("set", "url_passthrough", true);
466
+ gtag("consent", "default", {
467
+ ...signals((id) => consent.isRequired(id)),
468
+ wait_for_update: options.waitForUpdate ?? 500,
469
+ ...options.region ? { region: [...options.region] } : {}
470
+ });
471
+ let last = "";
472
+ const sync = () => {
473
+ if (consent.getSnapshot().status !== "decided" && last === "") return;
474
+ const next = signals((id) => consent.isGranted(id));
475
+ const key = JSON.stringify(next);
476
+ if (key === last) return;
477
+ last = key;
478
+ gtag("consent", "update", next);
479
+ };
480
+ sync();
481
+ return consent.subscribe(sync);
482
+ }
483
+ //#endregion
484
+ //#region src/integrations/unblock-scripts.ts
485
+ /**
486
+ * Hold third-party scripts and embeds back until their category is granted — mark them up blocked and
487
+ * this activates them the moment consent allows (on load, and on every later change):
488
+ *
489
+ * ```html
490
+ * <!-- a script: type="text/plain" so the browser doesn't run it; data-type restores a module type -->
491
+ * <script type="text/plain" data-consent="statistics" src="https://example.com/analytics.js"><\/script>
492
+ * <script type="text/plain" data-consent="marketing">trackPageView()<\/script>
493
+ *
494
+ * <!-- with a vendor: also only while that vendor is used in the category -->
495
+ * <script type="text/plain" data-consent="marketing" data-consent-vendor="meta_pixel">fbq(…)<\/script>
496
+ *
497
+ * <!-- an iframe / img: data-src instead of src -->
498
+ * <iframe data-consent="marketing" data-src="https://www.youtube-nocookie.com/embed/…"></iframe>
499
+ * ```
500
+ *
501
+ * A script is replaced by a fresh `<script>` copy (the only way to make the browser run it), its
502
+ * CSP `nonce` included; an embed gets its `src` from `data-src`. Activation is one-way: a revoked category can't un-run a
503
+ * script — reload the page from `onChange` when something is withdrawn. Returns a stop function.
504
+ */
505
+ function unblockScripts(consent, options = {}) {
506
+ if (typeof document === "undefined") return () => {};
507
+ const root = options.root ?? document;
508
+ const attr = options.attribute ?? "data-consent";
509
+ const vendorAttr = options.vendorAttribute ?? "data-consent-vendor";
510
+ const allowed = (el) => {
511
+ const ids = (el.getAttribute(attr) ?? "").split(/\s+/).filter(Boolean);
512
+ const vendor = el.getAttribute(vendorAttr) ?? void 0;
513
+ return ids.length > 0 && ids.every((id) => consent.isGranted(id, vendor));
514
+ };
515
+ const activate = () => {
516
+ for (const el of Array.from(root.querySelectorAll(`script[type="text/plain"][${attr}]`))) {
517
+ if (!allowed(el)) continue;
518
+ const script = document.createElement("script");
519
+ for (const { name, value } of Array.from(el.attributes)) {
520
+ if (name === "type" || name === "data-type") continue;
521
+ script.setAttribute(name, value);
522
+ }
523
+ const type = el.getAttribute("data-type");
524
+ if (type) script.setAttribute("type", type);
525
+ const { nonce } = el;
526
+ if (nonce) script.nonce = nonce;
527
+ if (!el.hasAttribute("src")) script.text = el.textContent ?? "";
528
+ el.replaceWith(script);
529
+ }
530
+ for (const el of Array.from(root.querySelectorAll(`[${attr}][data-src]:not(script)`))) {
531
+ if (!allowed(el)) continue;
532
+ const src = el.getAttribute("data-src");
533
+ el.removeAttribute("data-src");
534
+ if (src) el.setAttribute("src", src);
535
+ }
536
+ };
537
+ activate();
538
+ const unsubscribe = consent.subscribe(activate);
539
+ let observer;
540
+ if ((options.observe ?? true) && typeof MutationObserver !== "undefined") {
541
+ observer = new MutationObserver((records) => {
542
+ if (records.some((r) => r.addedNodes.length > 0)) activate();
543
+ });
544
+ const target = root instanceof Document ? root.documentElement : root;
545
+ observer.observe(target, {
546
+ childList: true,
547
+ subtree: true
548
+ });
549
+ }
550
+ return () => {
551
+ unsubscribe();
552
+ observer?.disconnect();
553
+ };
554
+ }
555
+ //#endregion
556
+ export { CONSENT_CATEGORIES, ConsentCookieFormatter, ConsentDecision, ConsentError, DEFAULT_GOOGLE_CONSENT_MAPPING, DEFAULT_MAX_AGE, DEFAULT_STORAGE_KEY, REQUIRED_CATEGORY, clearRevokedCookies, createConsent, googleConsentMode, isConsentCategoryId, unblockScripts };
557
+
558
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["#granted"],"sources":["../src/domain/consent-decision.ts","../src/consent.ts","../src/formatters/consent-cookie-formatter.ts","../src/integrations/clear-revoked-cookies.ts","../src/integrations/google-consent-mode.ts","../src/integrations/unblock-scripts.ts"],"sourcesContent":["import type { ConsentCategoryId } from '../categories'\nimport { ConsentError } from '../errors'\nimport type { StoredConsent } from '../types'\n\nexport interface ConsentDecisionInput {\n consent_id: string\n policy_version: string\n granted: Iterable<ConsentCategoryId>\n decided_at: number\n}\n\n/**\n * One visitor's answer to the consent question: which categories they granted, under which policy\n * version, and when. Immutable and always valid — the factory throws on a malformed input.\n *\n * Validity over time (policy version, expiry) is not the decision's concern: the consent instance\n * decides whether a stored decision still counts.\n */\nexport class ConsentDecision {\n readonly consent_id: string\n readonly policy_version: string\n /** When the decision was made, in epoch milliseconds. */\n readonly decided_at: number\n readonly #granted: ReadonlySet<ConsentCategoryId>\n\n private constructor(input: ConsentDecisionInput) {\n this.consent_id = input.consent_id\n this.policy_version = input.policy_version\n this.decided_at = input.decided_at\n this.#granted = new Set(input.granted)\n }\n\n /** @throws {ConsentError} on an empty `consent_id` / `policy_version` or a non-finite `decided_at`. */\n static new(input: ConsentDecisionInput): ConsentDecision {\n if (typeof input.consent_id !== 'string' || input.consent_id === '') {\n throw new ConsentError('A consent decision needs a non-empty consent_id.')\n }\n if (typeof input.policy_version !== 'string' || input.policy_version === '') {\n throw new ConsentError('A consent decision needs a non-empty policy_version.')\n }\n if (typeof input.decided_at !== 'number' || !Number.isFinite(input.decided_at)) {\n throw new ConsentError('A consent decision needs decided_at as finite epoch milliseconds.')\n }\n return new ConsentDecision(input)\n }\n\n /** Like {@link ConsentDecision.new}, but returns `null` instead of throwing. */\n static tryNew(input: ConsentDecisionInput): ConsentDecision | null {\n try {\n return ConsentDecision.new(input)\n } catch {\n return null\n }\n }\n\n /** Whether this decision grants the category. */\n isGranted(id: ConsentCategoryId): boolean {\n return this.#granted.has(id)\n }\n\n /** Every granted category id. */\n granted(): ConsentCategoryId[] {\n return [...this.#granted]\n }\n\n /** Same id, version, time and granted set. */\n equals(other: ConsentDecision): boolean {\n if (\n this.consent_id !== other.consent_id ||\n this.policy_version !== other.policy_version ||\n this.decided_at !== other.decided_at ||\n this.#granted.size !== other.#granted.size\n ) {\n return false\n }\n for (const id of this.#granted) if (!other.#granted.has(id)) return false\n return true\n }\n\n /** The serialized form kept in the store. */\n toJSON(): StoredConsent {\n return {\n consent_id: this.consent_id,\n policy_version: this.policy_version,\n granted: this.granted(),\n decided_at: this.decided_at,\n }\n }\n}\n","import { localStore } from '@luwiostack/storage'\nimport {\n CONSENT_CATEGORIES,\n type ConsentCategoryId,\n isConsentCategoryId,\n REQUIRED_CATEGORY,\n} from './categories'\nimport { ConsentDecision } from './domain/consent-decision'\nimport { ConsentError } from './errors'\nimport type {\n ConsentCategoriesConfig,\n ConsentCategory,\n ConsentConfig,\n ConsentCookie,\n ConsentCookieType,\n ConsentManager,\n ConsentSnapshot,\n ConsentVendor,\n StoredConsent,\n} from './types'\nimport { usedVendors } from './used-vendors'\n\n/** The key the default `localStorage` store keeps the decision behind. */\nexport const DEFAULT_STORAGE_KEY = 'luwio.consent'\n/** The default decision lifetime: 365 days. */\nexport const DEFAULT_MAX_AGE = 365 * 24 * 60 * 60 * 1000\n\n// A stored decision dated further ahead than this is invalid: it can't have been made yet, and\n// would otherwise never expire. The margin absorbs a clock adjusted slightly back.\nconst FUTURE_TOLERANCE = 5 * 60 * 1000\n\nconst PENDING: ConsentSnapshot = Object.freeze({ status: 'pending', decision: null })\n\nconst COOKIE_TYPES: ReadonlySet<ConsentCookieType> = new Set([\n 'http',\n 'local_storage',\n 'session_storage',\n 'indexed_db',\n 'pixel',\n])\n\n/** Checks one vendor declaration: an id, unique cookie names, valid categories and lifetimes. */\nfunction validateVendor(vendor: ConsentVendor, listedIn: ConsentCategoryId): void {\n if (typeof vendor?.id !== 'string' || vendor.id === '') {\n throw new ConsentError(`Category \"${listedIn}\": a vendor id must be non-empty.`)\n }\n const where = `Vendor \"${vendor.id}\"`\n if (!Array.isArray(vendor.cookies)) throw new ConsentError(`${where}: cookies must be an array.`)\n const names = new Set<string>()\n for (const cookie of vendor.cookies) {\n if (typeof cookie.name !== 'string' || cookie.name === '') {\n throw new ConsentError(`${where}: a cookie name must be non-empty.`)\n }\n if (names.has(cookie.name)) {\n throw new ConsentError(`${where}: duplicate cookie \"${cookie.name}\".`)\n }\n names.add(cookie.name)\n if (!isConsentCategoryId(cookie.category)) {\n throw new ConsentError(\n `${where}: cookie \"${cookie.name}\" needs a category (${CONSENT_CATEGORIES.join(', ')}).`,\n )\n }\n if (cookie.type !== undefined && !COOKIE_TYPES.has(cookie.type)) {\n throw new ConsentError(\n `${where}: cookie \"${cookie.name}\" has an unknown type \"${cookie.type}\".`,\n )\n }\n const { max_age } = cookie\n const validAge =\n max_age === 'session' ||\n max_age === 'persistent' ||\n (typeof max_age === 'number' && Number.isFinite(max_age) && max_age > 0)\n if (!validAge) {\n throw new ConsentError(\n `${where}: cookie \"${cookie.name}\" needs max_age as positive milliseconds, 'session' or 'persistent'.`,\n )\n }\n }\n}\n\n/**\n * Resolves the per-category config into the vendors the app actually uses: a vendor listed under a\n * category brings its cookies of that category, plus its necessary cookies (always allowed, and part\n * of any use of the service). A vendor listed under several categories is merged into one.\n */\nfunction resolveVendors(config: ConsentCategoriesConfig): {\n vendors: ConsentVendor[]\n listed: Record<ConsentCategoryId, string[]>\n} {\n if (typeof config !== 'object' || config === null || Array.isArray(config)) {\n throw new ConsentError('categories must be an object of category id → vendors.')\n }\n for (const key of Object.keys(config)) {\n if (!isConsentCategoryId(key)) {\n throw new ConsentError(\n `Unknown consent category \"${key}\" — use ${CONSENT_CATEGORIES.join(', ')}.`,\n )\n }\n }\n const merged = new Map<string, { vendor: ConsentVendor; cookies: Map<string, ConsentCookie> }>()\n const listed = Object.fromEntries(CONSENT_CATEGORIES.map((id) => [id, [] as string[]])) as Record<\n ConsentCategoryId,\n string[]\n >\n for (const category of CONSENT_CATEGORIES) {\n const inCategory = config[category]\n if (inCategory === undefined) continue\n if (!Array.isArray(inCategory as unknown)) {\n throw new ConsentError(`Category \"${category}\": vendors must be an array.`)\n }\n const seen = new Set<string>()\n for (const vendor of inCategory) {\n validateVendor(vendor, category)\n const where = `Category \"${category}\", vendor \"${vendor.id}\"`\n if (seen.has(vendor.id)) throw new ConsentError(`${where}: duplicate vendor.`)\n seen.add(vendor.id)\n listed[category].push(vendor.id)\n const picked = vendor.cookies.filter((c) => c.category === category)\n if (picked.length === 0) {\n throw new ConsentError(`${where}: the vendor has no ${category} cookies.`)\n }\n const entry = merged.get(vendor.id) ?? { vendor, cookies: new Map() }\n for (const cookie of vendor.cookies) {\n if (cookie.category === category || cookie.category === REQUIRED_CATEGORY) {\n entry.cookies.set(cookie.name, cookie)\n }\n }\n merged.set(vendor.id, entry)\n }\n }\n const vendors = [...merged.values()].map(({ vendor, cookies }) => ({\n ...vendor,\n // Keep the declaration's own cookie order.\n cookies: vendor.cookies.filter((c) => cookies.has(c.name)),\n }))\n return { vendors, listed }\n}\n\n// The id of an expired / old-version record is reused so a consent log stays linked — but only when\n// it's a usable string (the stored value may have been tampered with).\nfunction reusableId(record: StoredConsent | null): string | null {\n const id = record?.consent_id\n return typeof id === 'string' && id !== '' ? id : null\n}\n\nfunction randomId(): string {\n const c = globalThis.crypto\n if (c && typeof c.randomUUID === 'function') return c.randomUUID()\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`\n}\n\n/**\n * Create a consent instance: per category, the vendors the app uses there (a vendor brings only its\n * cookies of that category, plus its necessary ones), where the decision is kept, and when it must\n * be asked again. Create it once (module\n * scope is fine — storage is only touched on access, so it's SSR-safe) and hand it to\n * `<Consent consent={…}>` in React, or use it directly.\n *\n * ```ts\n * import { googleAnalytics, youtube } from '@luwiostack/cookie-consent/vendors'\n *\n * const consent = createConsent({\n * categories: {\n * statistics: [googleAnalytics()],\n * preferences: [youtube()], // the embed only — no YouTube tracking cookies\n * },\n * policyVersion: 2,\n * })\n * consent.isGranted('preferences', 'youtube') // the embed may load\n * consent.isGranted('marketing', 'youtube') // false — not used there\n * ```\n *\n * @throws {ConsentError} for an invalid `maxAge`, an unknown category, or an invalid vendor (listed\n * twice in a category, no cookies of the category it's listed in, duplicate cookie, empty name,\n * missing cookie category, bad `max_age` / `type`).\n */\nexport function createConsent(config: ConsentConfig = {}): ConsentManager {\n const { vendors, listed } = resolveVendors(config.categories ?? {})\n\n // Each category with the vendors that have cookies in it, cookies narrowed to that category: the\n // ones listed there in config order, then (for necessary) the others that bring necessary cookies.\n const byId = new Map(vendors.map((v) => [v.id, v]))\n const categories: readonly ConsentCategory[] = CONSENT_CATEGORIES.map((id) => {\n const ids = [...new Set([...listed[id], ...vendors.map((v) => v.id)])]\n return {\n id,\n required: id === REQUIRED_CATEGORY,\n vendors: ids.flatMap((vendorId) => {\n const vendor = byId.get(vendorId) as ConsentVendor\n const cookies = vendor.cookies.filter((c) => c.category === id)\n return cookies.length > 0 ? [{ ...vendor, cookies }] : []\n }),\n }\n })\n const usedIn = usedVendors(categories)\n\n const maxAge = config.maxAge ?? DEFAULT_MAX_AGE\n if (typeof maxAge !== 'number' || Number.isNaN(maxAge) || maxAge <= 0) {\n throw new ConsentError('maxAge must be a positive number of milliseconds.')\n }\n const policyVersion = String(config.policyVersion ?? 1)\n // Persisting the decision is best-effort: where storage is blocked or full, the default store fails\n // quietly instead of throwing out of acceptAll() & co. A store you pass in keeps its own onError.\n const store =\n config.store ?? localStore<StoredConsent>(DEFAULT_STORAGE_KEY, { onError: 'ignore' })\n const now = config.now ?? Date.now\n\n // A decision the store didn't keep (storage blocked or full, a store with onError 'ignore') is held\n // here for the rest of the page's life — so the banner closes and the visitor's choice applies,\n // instead of being asked again on every click. `undefined`: the store is the source of truth.\n let unsaved: StoredConsent | null | undefined\n const listeners = new Set<() => void>()\n const notify = () => {\n for (const fn of [...listeners]) fn()\n }\n const read = (): StoredConsent | null => (unsaved !== undefined ? unsaved : store.read())\n\n // Snapshot memo: the store's read() is referentially stable between changes, so caching on the raw\n // record (plus whether it has expired since) keeps getSnapshot() stable for useSyncExternalStore.\n let lastRecord: StoredConsent | null | undefined\n let lastExpired = false\n let lastSnapshot: ConsentSnapshot = PENDING\n\n function toDecision(record: StoredConsent): ConsentDecision | null {\n if (record.policy_version !== policyVersion) return null\n if (!Array.isArray(record.granted)) return null\n // Unknown ids (a tampered record) are dropped; necessary is always in.\n const granted = new Set<ConsentCategoryId>([REQUIRED_CATEGORY])\n for (const id of record.granted) if (isConsentCategoryId(id)) granted.add(id)\n return ConsentDecision.tryNew({ ...record, granted })\n }\n\n function getSnapshot(): ConsentSnapshot {\n const record = read()\n const age = record === null ? 0 : now() - record.decided_at\n const expired = record !== null && (age > maxAge || age < -FUTURE_TOLERANCE)\n if (record === lastRecord && expired === lastExpired) return lastSnapshot\n lastRecord = record\n lastExpired = expired\n const decision = record && !expired ? toDecision(record) : null\n lastSnapshot = decision ? Object.freeze({ status: 'decided', decision }) : PENDING\n return lastSnapshot\n }\n\n function current(): ConsentDecision | null {\n return getSnapshot().decision\n }\n\n function commit(granted: Iterable<ConsentCategoryId>): ConsentDecision {\n const previous = current()\n const set = new Set<ConsentCategoryId>([REQUIRED_CATEGORY])\n for (const id of granted) if (isConsentCategoryId(id)) set.add(id)\n const next = ConsentDecision.new({\n // Keep the visitor's consent id across changes, so a consent log can link them.\n consent_id: previous?.consent_id ?? reusableId(read()) ?? randomId(),\n policy_version: policyVersion,\n // Keep the categories' configured order in storage.\n granted: CONSENT_CATEGORIES.filter((id) => set.has(id)),\n decided_at: now(),\n })\n const record = next.toJSON()\n store.write(record)\n // Did it land? A store that fails quietly reads back the old value (or nothing).\n const kept = store.read()\n const landed = kept?.consent_id === record.consent_id && kept?.decided_at === record.decided_at\n unsaved = landed ? undefined : record\n if (!landed) notify() // the store announced nothing\n config.onChange?.(next, previous)\n return next\n }\n\n const isRequired = (id: ConsentCategoryId) => id === REQUIRED_CATEGORY\n const isGranted = (id: ConsentCategoryId, vendorId?: string) =>\n (vendorId === undefined || usedIn[id].has(vendorId)) &&\n (isRequired(id) || (current()?.isGranted(id) ?? false))\n\n return {\n categories,\n vendors,\n policyVersion,\n getSnapshot,\n subscribe: (onChange) => {\n listeners.add(onChange)\n const unsubscribe = store.subscribe(onChange)\n return () => {\n listeners.delete(onChange)\n unsubscribe()\n }\n },\n isGranted,\n isRequired,\n acceptAll: () => commit(CONSENT_CATEGORIES),\n rejectAll: () => commit([]),\n save: (granted) => commit(granted),\n grant: (...grant) => commit([...(current()?.granted() ?? []), ...grant]),\n revoke: (...revoke) => {\n const drop = new Set(revoke)\n return commit((current()?.granted() ?? []).filter((id) => !drop.has(id)))\n },\n reset: () => {\n const previous = current()\n store.clear()\n if (unsaved !== undefined) {\n unsaved = undefined\n notify()\n }\n config.onChange?.(null, previous)\n },\n }\n}\n","import type { ConsentCookie } from '../types'\n\nexport interface ConsentCookieFormatOptions {\n /** How unit names are written: `long` (\"2 years\"), `short` (\"2 yrs\"), `narrow` (\"2y\"). Default `long`. */\n unitDisplay?: 'long' | 'short' | 'narrow'\n}\n\nconst SECOND = 1000\nconst MINUTE = 60 * SECOND\nconst HOUR = 60 * MINUTE\nconst DAY = 24 * HOUR\n\n// Largest first. A month counts as 30 days and a year as 365 — how cookie declarations are written\n// (\"3 months\" for 90 days, \"13 months\" for 390), not calendar arithmetic.\nconst UNITS = [\n ['year', 365 * DAY],\n ['month', 30 * DAY],\n ['day', DAY],\n ['hour', HOUR],\n ['minute', MINUTE],\n ['second', SECOND],\n] as const\n\n/** Renders a cookie declaration's values for people. */\nexport class ConsentCookieFormatter {\n /**\n * A cookie's lifetime in `locale`, in the largest unit that divides it evenly: 2 years, 3 months,\n * 400 days, 30 minutes — falling back to whole days (or the largest unit that fits) when nothing\n * divides evenly. Returns `null` for `'session'` and `'persistent'`: those are words, so render\n * them through your own translations.\n */\n static formatLocale(\n cookie: Pick<ConsentCookie, 'max_age'>,\n locale: Intl.Locale,\n options: ConsentCookieFormatOptions = {},\n ): string | null {\n const { max_age } = cookie\n if (typeof max_age !== 'number') return null\n const unitDisplay = options.unitDisplay ?? 'long'\n const exact = UNITS.find(([, ms]) => max_age >= ms && max_age % ms === 0)\n const [unit, ms] =\n exact ?? (max_age >= DAY ? UNITS[2] : (UNITS.find(([, u]) => max_age >= u) ?? UNITS[5]))\n const value = Math.max(1, Math.round(max_age / ms))\n return new Intl.NumberFormat(locale.toString(), { style: 'unit', unit, unitDisplay }).format(\n value,\n )\n }\n}\n","import { REQUIRED_CATEGORY } from '../categories'\nimport type { ConsentCookie, ConsentManager } from '../types'\n\nexport interface ClearRevokedCookiesOptions {\n /**\n * Called once per item actually removed, with the declaration and the real name (a wildcard\n * `_ga_*` resolves to `_ga_ABC123`) — to log it, or to reload the page so running scripts stop.\n */\n onClear?: (cookie: ConsentCookie, actualName: string) => void\n}\n\n/** A declared name as a matcher: `*` matches any run of characters (`_ga_*`, `ttcsid*`). */\nfunction matcher(name: string): (actual: string) => boolean {\n if (!name.includes('*')) return (actual) => actual === name\n const pattern = name.split('*').map((part) => part.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n const re = new RegExp(`^${pattern.join('.*')}$`)\n return (actual) => re.test(actual)\n}\n\n/**\n * The domains a first-party cookie may have been set for: none (host-only), the host itself, and\n * each parent domain (`www.shop.example.com` → `shop.example.com`, `example.com`). Analytics tags\n * usually set theirs on the registrable domain, so deleting needs the same `Domain` attribute.\n * A bare top-level domain (`com`) is never a valid cookie domain, so it's left out.\n * @internal\n */\nexport function domainCandidates(hostname: string): (string | undefined)[] {\n const parts = hostname.split('.')\n const parents: string[] = []\n for (let i = 0; i < parts.length - 1; i++) parents.push(parts.slice(i).join('.'))\n return [undefined, ...parents]\n}\n\n/** The paths a cookie may have been set for, from this page up to the root: `/a/b` → `/a/b`, `/a`, `/`. @internal */\nexport function pathCandidates(pathname: string): string[] {\n const segments = pathname.split('/').filter(Boolean)\n const paths = ['/']\n for (let i = 1; i <= segments.length; i++) paths.push(`/${segments.slice(0, i).join('/')}`)\n return paths\n}\n\nfunction cookieNames(doc: Document): string[] {\n return doc.cookie\n .split(';')\n .map((pair) => pair.slice(0, pair.indexOf('=') === -1 ? undefined : pair.indexOf('=')).trim())\n .filter(Boolean)\n}\n\nfunction expireCookie(doc: Document, name: string): void {\n const { hostname, pathname } = doc.location\n for (const domain of domainCandidates(hostname)) {\n for (const path of pathCandidates(pathname)) {\n doc.cookie = `${name}=; Path=${path}${domain ? `; Domain=${domain}` : ''}; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`\n }\n }\n}\n\nfunction storageKeys(storage: Storage): string[] {\n const keys: string[] = []\n for (let i = 0; i < storage.length; i++) {\n const key = storage.key(i)\n if (key !== null) keys.push(key)\n }\n return keys\n}\n\n/**\n * Remove what a withdrawn category left behind. At start and on every change, the declared cookies\n * and storage items of every category that isn't granted are deleted — after \"withdraw statistics\",\n * `_ga` and `_ga_*` are gone, not just unused. `necessary` is never touched, and a name a granted\n * category also declares is kept.\n *\n * Only **first-party** storage can be reached: cookies on your own domain (tried with every parent\n * domain and path, since tags set them broadly), `localStorage` / `sessionStorage` items and\n * IndexedDB databases. A third-party cookie (`IDE` on doubleclick.net) lives on another site and\n * can't be removed from yours; `HttpOnly` cookies only by your server. Scripts already running keep\n * running — reload the page (e.g. from `onClear`) to stop them.\n *\n * Returns a stop function. A no-op on the server.\n */\nexport function clearRevokedCookies(\n consent: ConsentManager,\n options: ClearRevokedCookiesOptions = {},\n): () => void {\n if (typeof document === 'undefined') return () => {}\n\n const clear = () => {\n // What a granted category declares stays — even when a revoked one declares the same name.\n const kept: ((actual: string) => boolean)[] = []\n const revoked: ConsentCookie[] = []\n for (const category of consent.categories) {\n const granted = category.id === REQUIRED_CATEGORY || consent.isGranted(category.id)\n for (const vendor of category.vendors) {\n for (const cookie of vendor.cookies) {\n if (granted) kept.push(matcher(cookie.name))\n else revoked.push(cookie)\n }\n }\n }\n if (revoked.length === 0) return\n const isKept = (actual: string) => kept.some((matches) => matches(actual))\n const cleared = (cookie: ConsentCookie, actual: string) => options.onClear?.(cookie, actual)\n\n for (const cookie of revoked) {\n const matches = matcher(cookie.name)\n const type = cookie.type ?? 'http'\n if (type === 'http') {\n for (const actual of cookieNames(document)) {\n if (!matches(actual) || isKept(actual)) continue\n expireCookie(document, actual)\n // Reported only once it's really gone (no domain/path variant may have matched).\n if (!cookieNames(document).includes(actual)) cleared(cookie, actual)\n }\n } else if (type === 'local_storage' || type === 'session_storage') {\n let storage: Storage | undefined\n try {\n storage = type === 'local_storage' ? window.localStorage : window.sessionStorage\n } catch {\n continue // Storage blocked: there's nothing to remove either.\n }\n for (const actual of storageKeys(storage)) {\n if (!matches(actual) || isKept(actual)) continue\n storage.removeItem(actual)\n cleared(cookie, actual)\n }\n } else if (type === 'indexed_db' && typeof indexedDB !== 'undefined') {\n if (typeof indexedDB.databases === 'function') {\n void indexedDB.databases().then((databases) => {\n for (const { name } of databases) {\n if (!name || !matches(name) || isKept(name)) continue\n indexedDB.deleteDatabase(name)\n cleared(cookie, name)\n }\n })\n } else if (!cookie.name.includes('*') && !isKept(cookie.name)) {\n // No list of databases (older browsers): delete by exact name — deleting a database that\n // doesn't exist is harmless, but it isn't reported, since it may never have been there.\n indexedDB.deleteDatabase(cookie.name)\n }\n }\n // 'pixel': nothing is stored on the visitor's device.\n }\n }\n\n clear()\n return consent.subscribe(clear)\n}\n","import type { ConsentCategoryId } from '../categories'\nimport type { ConsentManager } from '../types'\n\n/** The Google Consent Mode v2 signals. */\nexport type GoogleConsentSignal =\n | 'ad_storage'\n | 'ad_user_data'\n | 'ad_personalization'\n | 'analytics_storage'\n | 'functionality_storage'\n | 'personalization_storage'\n | 'security_storage'\n\nexport type GoogleConsentValue = 'granted' | 'denied'\n\n/** Which category (or categories — all must be granted) drives each signal. Unmapped signals aren't sent. */\nexport type GoogleConsentMapping = Partial<\n Record<GoogleConsentSignal, ConsentCategoryId | readonly ConsentCategoryId[]>\n>\n\n/** The standard mapping of Google's signals onto the fixed categories — the default. */\nexport const DEFAULT_GOOGLE_CONSENT_MAPPING = {\n ad_storage: 'marketing',\n ad_user_data: 'marketing',\n ad_personalization: 'marketing',\n analytics_storage: 'statistics',\n functionality_storage: 'preferences',\n personalization_storage: 'preferences',\n security_storage: 'necessary',\n} as const satisfies Required<GoogleConsentMapping>\n\ntype Gtag = (...args: unknown[]) => void\n\nexport interface GoogleConsentModeOptions {\n /**\n * Which category drives each signal. Default {@link DEFAULT_GOOGLE_CONSENT_MAPPING} (ads →\n * marketing, analytics → statistics, functionality / personalization → preferences, security →\n * necessary). A custom mapping sends only the signals it lists; a signal mapped to several\n * categories is granted only when all are.\n */\n mapping?: GoogleConsentMapping\n /** Milliseconds Google tags wait for an `update` after the `default` command. Default `500`. */\n waitForUpdate?: number\n /** Restrict the `default` command to these ISO 3166-2 regions (e.g. `['BE', 'NL']`). */\n region?: readonly string[]\n /** Send `ads_data_redaction: true` while ad storage is denied. Default `false`. */\n adsDataRedaction?: boolean\n /** Send `url_passthrough: true`. Default `false`. */\n urlPassthrough?: boolean\n /** The `gtag` function. Default `window.gtag`, defined as the standard `dataLayer` stub if absent. */\n gtag?: Gtag\n}\n\ntype GtagWindow = Window & { dataLayer?: unknown[]; gtag?: Gtag }\n\nfunction resolveGtag(): Gtag | undefined {\n if (typeof window === 'undefined') return undefined\n const w = window as GtagWindow\n if (typeof w.gtag === 'function') return w.gtag\n w.dataLayer = w.dataLayer ?? []\n const dataLayer = w.dataLayer\n // Google's own stub: it must push the `arguments` object, not an array — gtag.js tells them apart.\n w.gtag = function gtag() {\n // biome-ignore lint/complexity/noArguments: gtag.js requires the Arguments object\n dataLayer.push(arguments)\n }\n return w.gtag\n}\n\n/**\n * Wire a consent instance to Google Consent Mode v2: sends `gtag('consent', 'default', …)` with every\n * mapped signal denied (signals mapped to required categories granted), then an `update` with the\n * visitor's decision — immediately when one is stored, and again on every change.\n *\n * Call it **before** the Google tag (gtag.js / GTM) loads, so the default is in place for its first\n * hit. Returns an unsubscribe. A no-op on the server.\n */\nexport function googleConsentMode(\n consent: ConsentManager,\n options: GoogleConsentModeOptions = {},\n): () => void {\n const gtag = options.gtag ?? resolveGtag()\n if (!gtag) return () => {}\n\n type Id = ConsentCategoryId\n const entries = Object.entries(options.mapping ?? DEFAULT_GOOGLE_CONSENT_MAPPING) as [\n GoogleConsentSignal,\n Id | readonly Id[],\n ][]\n\n const signals = (isGranted: (id: Id) => boolean) => {\n const out: Partial<Record<GoogleConsentSignal, GoogleConsentValue>> = {}\n for (const [signal, cat] of entries) {\n const list = (typeof cat === 'string' ? [cat] : cat) as readonly Id[]\n out[signal] = list.every(isGranted) ? 'granted' : 'denied'\n }\n return out\n }\n\n if (options.adsDataRedaction) gtag('set', 'ads_data_redaction', true)\n if (options.urlPassthrough) gtag('set', 'url_passthrough', true)\n\n gtag('consent', 'default', {\n ...signals((id) => consent.isRequired(id)),\n wait_for_update: options.waitForUpdate ?? 500,\n ...(options.region ? { region: [...options.region] } : {}),\n })\n\n let last = ''\n const sync = () => {\n if (consent.getSnapshot().status !== 'decided' && last === '') return\n const next = signals((id) => consent.isGranted(id))\n const key = JSON.stringify(next)\n if (key === last) return\n last = key\n gtag('consent', 'update', next)\n }\n sync()\n return consent.subscribe(sync)\n}\n","import type { ConsentCategoryId } from '../categories'\nimport type { ConsentManager } from '../types'\n\nexport interface UnblockScriptsOptions {\n /** Where to look. Default `document`. */\n root?: ParentNode\n /** The attribute naming the required categories (space-separated, all must be granted). Default `data-consent`. */\n attribute?: string\n /**\n * The attribute naming the vendor, which must then be used in those categories — an element whose\n * vendor isn't configured there stays blocked. Default `data-consent-vendor`.\n */\n vendorAttribute?: string\n /** Also activate matching elements added to the page later (a `MutationObserver`). Default `true`. */\n observe?: boolean\n}\n\n/**\n * Hold third-party scripts and embeds back until their category is granted — mark them up blocked and\n * this activates them the moment consent allows (on load, and on every later change):\n *\n * ```html\n * <!-- a script: type=\"text/plain\" so the browser doesn't run it; data-type restores a module type -->\n * <script type=\"text/plain\" data-consent=\"statistics\" src=\"https://example.com/analytics.js\"></script>\n * <script type=\"text/plain\" data-consent=\"marketing\">trackPageView()</script>\n *\n * <!-- with a vendor: also only while that vendor is used in the category -->\n * <script type=\"text/plain\" data-consent=\"marketing\" data-consent-vendor=\"meta_pixel\">fbq(…)</script>\n *\n * <!-- an iframe / img: data-src instead of src -->\n * <iframe data-consent=\"marketing\" data-src=\"https://www.youtube-nocookie.com/embed/…\"></iframe>\n * ```\n *\n * A script is replaced by a fresh `<script>` copy (the only way to make the browser run it), its\n * CSP `nonce` included; an embed gets its `src` from `data-src`. Activation is one-way: a revoked category can't un-run a\n * script — reload the page from `onChange` when something is withdrawn. Returns a stop function.\n */\nexport function unblockScripts(\n consent: ConsentManager,\n options: UnblockScriptsOptions = {},\n): () => void {\n if (typeof document === 'undefined') return () => {}\n const root = options.root ?? document\n const attr = options.attribute ?? 'data-consent'\n const vendorAttr = options.vendorAttribute ?? 'data-consent-vendor'\n\n const allowed = (el: Element) => {\n const ids = (el.getAttribute(attr) ?? '').split(/\\s+/).filter(Boolean) as ConsentCategoryId[]\n const vendor = el.getAttribute(vendorAttr) ?? undefined\n return ids.length > 0 && ids.every((id) => consent.isGranted(id, vendor))\n }\n\n const activate = () => {\n for (const el of Array.from(root.querySelectorAll(`script[type=\"text/plain\"][${attr}]`))) {\n if (!allowed(el)) continue\n const script = document.createElement('script')\n for (const { name, value } of Array.from(el.attributes)) {\n if (name === 'type' || name === 'data-type') continue\n script.setAttribute(name, value)\n }\n const type = el.getAttribute('data-type')\n if (type) script.setAttribute('type', type)\n // Under a Content-Security-Policy header, browsers hide a script's nonce from getAttribute()\n // (\"nonce hiding\") — only the property keeps it. Without this the copy fails the CSP check.\n const { nonce } = el as HTMLScriptElement\n if (nonce) script.nonce = nonce\n if (!el.hasAttribute('src')) script.text = el.textContent ?? ''\n el.replaceWith(script)\n }\n for (const el of Array.from(root.querySelectorAll(`[${attr}][data-src]:not(script)`))) {\n if (!allowed(el)) continue\n const src = el.getAttribute('data-src')\n el.removeAttribute('data-src')\n if (src) el.setAttribute('src', src)\n }\n }\n\n activate()\n const unsubscribe = consent.subscribe(activate)\n\n let observer: MutationObserver | undefined\n if ((options.observe ?? true) && typeof MutationObserver !== 'undefined') {\n observer = new MutationObserver((records) => {\n if (records.some((r) => r.addedNodes.length > 0)) activate()\n })\n const target = root instanceof Document ? root.documentElement : (root as Node)\n observer.observe(target, { childList: true, subtree: true })\n }\n\n return () => {\n unsubscribe()\n observer?.disconnect()\n }\n}\n"],"mappings":";;;;;;;;;;;AAkBA,IAAa,kBAAb,MAAa,gBAAgB;CAC3B;CACA;;CAEA;CACA;CAEA,YAAoB,OAA6B;EAC/C,KAAK,aAAa,MAAM;EACxB,KAAK,iBAAiB,MAAM;EAC5B,KAAK,aAAa,MAAM;EACxB,KAAKA,WA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