@luwiostack/cookie-consent 0.0.0-stage → 0.2.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 { a as REQUIRED_CATEGORY, i as CONSENT_CATEGORIES, n as toConsentVendor, o as isConsentCategoryId, r as ConsentError, t as categoryMachineName } from "./machine-names-DAJioLt5.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
+ validateTransfers(vendor.transfers, where);
86
+ const names = /* @__PURE__ */ new Set();
87
+ for (const cookie of vendor.cookies) {
88
+ if (typeof cookie !== "object" || cookie === null) throw new ConsentError(`${where}: every cookie must be an object.`);
89
+ if (typeof cookie.name !== "string" || cookie.name === "") throw new ConsentError(`${where}: a cookie name must be non-empty.`);
90
+ if (names.has(cookie.name)) throw new ConsentError(`${where}: duplicate cookie "${cookie.name}".`);
91
+ names.add(cookie.name);
92
+ if (!isConsentCategoryId(cookie.category)) throw new ConsentError(`${where}: cookie "${cookie.name}" needs a category (${CONSENT_CATEGORIES.join(", ")}).`);
93
+ if (cookie.type !== void 0 && !COOKIE_TYPES.has(cookie.type)) throw new ConsentError(`${where}: cookie "${cookie.name}" has an unknown type "${cookie.type}".`);
94
+ const { max_age } = cookie;
95
+ 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'.`);
96
+ if (cookie.domain !== void 0 && (typeof cookie.domain !== "string" || !DOMAIN.test(cookie.domain))) throw new ConsentError(`${where}: cookie "${cookie.name}" needs domain as a host name like ".youtube.com", or none for the site's own domain.`);
97
+ }
98
+ }
99
+ /** A cookie domain: a host name, optionally with a leading dot, no scheme, port or path. */
100
+ const DOMAIN = /^\.?[a-z0-9-]+(\.[a-z0-9-]+)+$/i;
101
+ const SAFEGUARDS = /* @__PURE__ */ new Set([
102
+ "adequacy",
103
+ "dpf",
104
+ "scc",
105
+ "bcr"
106
+ ]);
107
+ /** Transfers: absent, or per unique ISO alpha-2 country at least one known safeguard. */
108
+ function validateTransfers(transfers, where) {
109
+ if (transfers === void 0) return;
110
+ if (!Array.isArray(transfers)) throw new ConsentError(`${where}: transfers must be an array.`);
111
+ const countries = /* @__PURE__ */ new Set();
112
+ for (const transfer of transfers) {
113
+ const country = transfer?.country;
114
+ if (typeof country !== "string" || !/^[A-Z]{2}$/.test(country)) throw new ConsentError(`${where}: a transfer needs country as ISO alpha-2, e.g. "US".`);
115
+ if (countries.has(country)) throw new ConsentError(`${where}: duplicate transfer "${country}".`);
116
+ countries.add(country);
117
+ const { safeguards } = transfer;
118
+ if (!Array.isArray(safeguards) || safeguards.length === 0 || !safeguards.every((s) => SAFEGUARDS.has(s))) throw new ConsentError(`${where}: transfer "${country}" needs safeguards from ${[...SAFEGUARDS].join(", ")}.`);
119
+ }
120
+ }
121
+ /**
122
+ * Resolves the per-category config into the vendors the app actually uses: a vendor listed under a
123
+ * category brings its cookies of that category, plus its necessary cookies (always allowed, and part
124
+ * of any use of the service). A vendor listed under several categories is merged into one.
125
+ */
126
+ function resolveVendors(config) {
127
+ if (typeof config !== "object" || config === null || Array.isArray(config)) throw new ConsentError("categories must be an object of category id → vendors.");
128
+ for (const key of Object.keys(config)) if (!isConsentCategoryId(key)) throw new ConsentError(`Unknown consent category "${key}" — use ${CONSENT_CATEGORIES.join(", ")}.`);
129
+ const merged = /* @__PURE__ */ new Map();
130
+ const idByMachineName = /* @__PURE__ */ new Map();
131
+ const listed = Object.fromEntries(CONSENT_CATEGORIES.map((id) => [id, []]));
132
+ for (const category of CONSENT_CATEGORIES) {
133
+ const inCategory = config[category];
134
+ if (inCategory === void 0) continue;
135
+ if (!Array.isArray(inCategory)) throw new ConsentError(`Category "${category}": vendors must be an array.`);
136
+ const seen = /* @__PURE__ */ new Set();
137
+ for (const declaration of inCategory) {
138
+ validateVendor(declaration, category);
139
+ const vendor = toConsentVendor(declaration);
140
+ const other = idByMachineName.get(vendor.machine_name);
141
+ if (other !== void 0 && other !== vendor.id) throw new ConsentError(`Vendors "${other}" and "${vendor.id}" have the same machine name "${vendor.machine_name}".`);
142
+ idByMachineName.set(vendor.machine_name, vendor.id);
143
+ const where = `Category "${category}", vendor "${vendor.id}"`;
144
+ if (seen.has(vendor.id)) throw new ConsentError(`${where}: duplicate vendor.`);
145
+ seen.add(vendor.id);
146
+ listed[category].push(vendor.id);
147
+ if (vendor.cookies.filter((c) => c.category === category).length === 0) throw new ConsentError(`${where}: the vendor has no ${category} cookies.`);
148
+ const entry = merged.get(vendor.id) ?? {
149
+ vendor,
150
+ cookies: /* @__PURE__ */ new Map()
151
+ };
152
+ if (entry.vendor !== vendor && !sameVendorInfo(entry.vendor, vendor)) throw new ConsentError(`Vendor "${vendor.id}" is declared differently in two categories (privacy_policy_url or transfers).`);
153
+ for (const cookie of vendor.cookies) {
154
+ if (cookie.category !== category && cookie.category !== "necessary") continue;
155
+ const known = entry.cookies.get(cookie.name);
156
+ if (known !== void 0 && !sameCookie(known, cookie)) throw new ConsentError(`Vendor "${vendor.id}": cookie "${cookie.name}" is declared differently in two categories.`);
157
+ const clash = [...entry.cookies.values()].find((c) => c.name !== cookie.name && c.machine_name === cookie.machine_name);
158
+ if (clash) throw new ConsentError(`Vendor "${vendor.id}": cookies "${clash.name}" and "${cookie.name}" have the same machine name "${cookie.machine_name}".`);
159
+ entry.cookies.set(cookie.name, cookie);
160
+ }
161
+ merged.set(vendor.id, entry);
162
+ }
163
+ }
164
+ return {
165
+ vendors: [...merged.values()].map(({ vendor, cookies }) => {
166
+ const order = vendor.cookies.map((c) => c.name).filter((name) => cookies.has(name));
167
+ const ordered = new Set(order);
168
+ for (const name of cookies.keys()) if (!ordered.has(name)) order.push(name);
169
+ return {
170
+ ...vendor,
171
+ cookies: order.flatMap((name) => cookies.get(name) ?? [])
172
+ };
173
+ }),
174
+ listed
175
+ };
176
+ }
177
+ function sameVendorInfo(a, b) {
178
+ return a.privacy_policy_url === b.privacy_policy_url && transfersKey(a.transfers) === transfersKey(b.transfers);
179
+ }
180
+ /** Transfers in a canonical form: the same countries and safeguards in any order compare equal. */
181
+ function transfersKey(transfers) {
182
+ if (transfers === void 0) return "none";
183
+ return transfers.map((t) => `${t.country}:${[...t.safeguards].sort().join(",")}`).sort().join(";");
184
+ }
185
+ function sameCookie(a, b) {
186
+ return a.category === b.category && (a.type ?? "http") === (b.type ?? "http") && a.max_age === b.max_age && a.domain === b.domain;
187
+ }
188
+ function reusableId(record) {
189
+ const id = record?.consent_id;
190
+ return typeof id === "string" && id !== "" ? id : null;
191
+ }
192
+ function randomId() {
193
+ const c = globalThis.crypto;
194
+ if (c && typeof c.randomUUID === "function") return c.randomUUID();
195
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
196
+ }
197
+ /**
198
+ * Create a consent instance: per category, the vendors the app uses there (a vendor brings only its
199
+ * cookies of that category, plus its necessary ones), where the decision is kept, and when it must
200
+ * be asked again. Create it once (module
201
+ * scope is fine — storage is only touched on access, so it's SSR-safe) and hand it to
202
+ * `<Consent consent={…}>` in React, or use it directly.
203
+ *
204
+ * ```ts
205
+ * import { googleAnalytics, youtube } from '@luwiostack/cookie-consent/vendors'
206
+ *
207
+ * const consent = createConsent({
208
+ * categories: {
209
+ * statistics: [googleAnalytics()],
210
+ * preferences: [youtube()], // the embed only — no YouTube tracking cookies
211
+ * },
212
+ * policyVersion: 2,
213
+ * })
214
+ * consent.isGranted('preferences', 'youtube') // the embed may load
215
+ * consent.isGranted('marketing', 'youtube') // false — not used there
216
+ * ```
217
+ *
218
+ * @throws {ConsentError} for an invalid `maxAge`, an unknown category, or an invalid vendor (listed
219
+ * twice in a category, no cookies of the category it's listed in, duplicate cookie, empty name,
220
+ * missing cookie category, bad `max_age` / `type`).
221
+ */
222
+ function createConsent(config = {}) {
223
+ const { vendors, listed } = resolveVendors(config.categories ?? {});
224
+ const byId = new Map(vendors.map((v) => [v.id, v]));
225
+ const categories = CONSENT_CATEGORIES.map((id) => {
226
+ const ids = [.../* @__PURE__ */ new Set([...listed[id], ...vendors.map((v) => v.id)])];
227
+ return {
228
+ id,
229
+ machine_name: categoryMachineName(id),
230
+ description_machine_name: `${categoryMachineName(id)}_description`,
231
+ required: id === REQUIRED_CATEGORY,
232
+ vendors: ids.flatMap((vendorId) => {
233
+ const vendor = byId.get(vendorId);
234
+ const cookies = vendor.cookies.filter((c) => c.category === id);
235
+ return cookies.length > 0 ? [{
236
+ ...vendor,
237
+ cookies
238
+ }] : [];
239
+ })
240
+ };
241
+ });
242
+ const usedIn = usedVendors(categories);
243
+ const maxAge = config.maxAge ?? 31536e6;
244
+ if (typeof maxAge !== "number" || Number.isNaN(maxAge) || maxAge <= 0) throw new ConsentError("maxAge must be a positive number of milliseconds.");
245
+ const rawVersion = config.policyVersion ?? 1;
246
+ if (!(typeof rawVersion === "string" && rawVersion !== "" || typeof rawVersion === "number" && Number.isFinite(rawVersion))) throw new ConsentError("policyVersion must be a non-empty string or a finite number.");
247
+ const policyVersion = String(rawVersion);
248
+ const store = config.store ?? localStore("luwio.consent", { onError: "ignore" });
249
+ const now = config.now ?? Date.now;
250
+ let unsaved;
251
+ const listeners = /* @__PURE__ */ new Set();
252
+ const notify = () => {
253
+ for (const fn of [...listeners]) fn();
254
+ };
255
+ const read = () => unsaved !== void 0 ? unsaved : store.read();
256
+ let lastRecord;
257
+ let lastExpired = false;
258
+ let lastSnapshot = PENDING;
259
+ function toDecision(record) {
260
+ if (record.policy_version !== policyVersion) return null;
261
+ if (!Array.isArray(record.granted)) return null;
262
+ const granted = /* @__PURE__ */ new Set([REQUIRED_CATEGORY]);
263
+ for (const id of record.granted) if (isConsentCategoryId(id)) granted.add(id);
264
+ return ConsentDecision.tryNew({
265
+ ...record,
266
+ granted
267
+ });
268
+ }
269
+ function getSnapshot() {
270
+ const record = read();
271
+ const age = record === null ? 0 : now() - record.decided_at;
272
+ const expired = record !== null && (age > maxAge || age < -3e5);
273
+ if (record === lastRecord && expired === lastExpired) return lastSnapshot;
274
+ lastRecord = record;
275
+ lastExpired = expired;
276
+ const decision = record && !expired ? toDecision(record) : null;
277
+ lastSnapshot = decision ? Object.freeze({
278
+ status: "decided",
279
+ decision
280
+ }) : PENDING;
281
+ return lastSnapshot;
282
+ }
283
+ function current() {
284
+ return getSnapshot().decision;
285
+ }
286
+ function commit(granted) {
287
+ const previous = current();
288
+ const set = /* @__PURE__ */ new Set([REQUIRED_CATEGORY]);
289
+ for (const id of granted) if (isConsentCategoryId(id)) set.add(id);
290
+ const next = ConsentDecision.new({
291
+ consent_id: previous?.consent_id ?? reusableId(read()) ?? randomId(),
292
+ policy_version: policyVersion,
293
+ granted: CONSENT_CATEGORIES.filter((id) => set.has(id)),
294
+ decided_at: now()
295
+ });
296
+ const record = next.toJSON();
297
+ store.write(record);
298
+ const kept = store.read();
299
+ const landed = kept?.consent_id === record.consent_id && kept?.decided_at === record.decided_at;
300
+ unsaved = landed ? void 0 : record;
301
+ if (!landed) notify();
302
+ config.onChange?.(next, previous);
303
+ return next;
304
+ }
305
+ const isRequired = (id) => id === REQUIRED_CATEGORY;
306
+ const isGranted = (id, vendorId) => (vendorId === void 0 || usedIn[id]?.has(vendorId) === true) && (isRequired(id) || (current()?.isGranted(id) ?? false));
307
+ return {
308
+ categories,
309
+ vendors,
310
+ policyVersion,
311
+ getSnapshot,
312
+ subscribe: (onChange) => {
313
+ listeners.add(onChange);
314
+ const unsubscribe = store.subscribe(onChange);
315
+ return () => {
316
+ listeners.delete(onChange);
317
+ unsubscribe();
318
+ };
319
+ },
320
+ isGranted,
321
+ isRequired,
322
+ acceptAll: () => commit(CONSENT_CATEGORIES),
323
+ rejectAll: () => commit([]),
324
+ save: (granted) => commit(granted),
325
+ grant: (...grant) => commit([...current()?.granted() ?? [], ...grant]),
326
+ revoke: (...revoke) => {
327
+ const drop = new Set(revoke);
328
+ return commit((current()?.granted() ?? []).filter((id) => !drop.has(id)));
329
+ },
330
+ reset: () => {
331
+ const previous = current();
332
+ store.clear();
333
+ if (unsaved !== void 0) {
334
+ unsaved = void 0;
335
+ notify();
336
+ }
337
+ config.onChange?.(null, previous);
338
+ }
339
+ };
340
+ }
341
+ //#endregion
342
+ //#region src/formatters/consent-cookie-formatter.ts
343
+ const SECOND = 1e3;
344
+ const MINUTE = 60 * SECOND;
345
+ const HOUR = 60 * MINUTE;
346
+ const DAY = 24 * HOUR;
347
+ const UNITS = [
348
+ ["year", 365 * DAY],
349
+ ["month", 30 * DAY],
350
+ ["day", DAY],
351
+ ["hour", HOUR],
352
+ ["minute", MINUTE],
353
+ ["second", SECOND]
354
+ ];
355
+ /** Renders a cookie declaration's values for people. */
356
+ var ConsentCookieFormatter = class {
357
+ /**
358
+ * A cookie's lifetime in `locale`, in the largest unit that divides it evenly: 2 years, 3 months,
359
+ * 400 days, 30 minutes — falling back to whole days (or the largest unit that fits) when nothing
360
+ * divides evenly. Returns `null` for `'session'` and `'persistent'`: those are words, so translate
361
+ * them — `formatLocale(cookie, locale) ?? t(cookie.max_age_machine_name)`.
362
+ */
363
+ static formatLocale(cookie, locale, options = {}) {
364
+ const { max_age } = cookie;
365
+ if (typeof max_age !== "number") return null;
366
+ const unitDisplay = options.unitDisplay ?? "long";
367
+ 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]);
368
+ const value = Math.max(1, Math.round(max_age / ms));
369
+ return new Intl.NumberFormat(locale.toString(), {
370
+ style: "unit",
371
+ unit,
372
+ unitDisplay
373
+ }).format(value);
374
+ }
375
+ };
376
+ //#endregion
377
+ //#region src/integrations/clear-revoked-cookies.ts
378
+ /** A declared name as a matcher: `*` matches any run of characters (`_ga_*`, `ttcsid*`). */
379
+ function matcher(name) {
380
+ if (!name.includes("*")) return (actual) => actual === name;
381
+ const pattern = name.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"));
382
+ const re = new RegExp(`^${pattern.join(".*")}$`);
383
+ return (actual) => re.test(actual);
384
+ }
385
+ /**
386
+ * The domains a first-party cookie may have been set for: none (host-only), the host itself, and
387
+ * each parent domain (`www.shop.example.com` → `shop.example.com`, `example.com`). Analytics tags
388
+ * usually set theirs on the registrable domain, so deleting needs the same `Domain` attribute.
389
+ * A bare top-level domain (`com`) is never a valid cookie domain, so it's left out.
390
+ * @internal
391
+ */
392
+ function domainCandidates(hostname) {
393
+ const parts = hostname.split(".");
394
+ const parents = [];
395
+ for (let i = 0; i < parts.length - 1; i++) parents.push(parts.slice(i).join("."));
396
+ return [void 0, ...parents];
397
+ }
398
+ /** The paths a cookie may have been set for, from this page up to the root: `/a/b` → `/a/b`, `/a`, `/`. @internal */
399
+ function pathCandidates(pathname) {
400
+ const segments = pathname.split("/").filter(Boolean);
401
+ const paths = ["/"];
402
+ for (let i = 1; i <= segments.length; i++) paths.push(`/${segments.slice(0, i).join("/")}`);
403
+ return paths;
404
+ }
405
+ function cookieNames(doc) {
406
+ return doc.cookie.split(";").map((pair) => pair.slice(0, pair.indexOf("=") === -1 ? void 0 : pair.indexOf("=")).trim()).filter(Boolean);
407
+ }
408
+ function expireCookie(doc, name) {
409
+ const { hostname, pathname } = doc.location;
410
+ 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`;
411
+ }
412
+ function storageKeys(storage) {
413
+ const keys = [];
414
+ for (let i = 0; i < storage.length; i++) {
415
+ const key = storage.key(i);
416
+ if (key !== null) keys.push(key);
417
+ }
418
+ return keys;
419
+ }
420
+ /**
421
+ * Remove what a withdrawn category left behind. At start and on every change, the declared cookies
422
+ * and storage items of every category that isn't granted are deleted — after "withdraw statistics",
423
+ * `_ga` and `_ga_*` are gone, not just unused. `necessary` is never touched, and a name a granted
424
+ * category also declares is kept.
425
+ *
426
+ * Only **first-party** storage can be reached: cookies on your own domain (tried with every parent
427
+ * domain and path, since tags set them broadly), `localStorage` / `sessionStorage` items and
428
+ * IndexedDB databases. A third-party cookie (declared with a `domain`, like `IDE` on
429
+ * doubleclick.net) lives on another site: it's skipped, so a first-party item that shares its name
430
+ * is never removed. `HttpOnly` cookies can only be removed by your server. Scripts already running keep
431
+ * running — reload the page (e.g. from `onClear`) to stop them.
432
+ *
433
+ * Returns a stop function. A no-op on the server.
434
+ */
435
+ function clearRevokedCookies(consent, options = {}) {
436
+ if (typeof document === "undefined") return () => {};
437
+ const clear = () => {
438
+ const kept = [];
439
+ const revoked = [];
440
+ for (const category of consent.categories) {
441
+ const granted = category.id === "necessary" || consent.isGranted(category.id);
442
+ for (const vendor of category.vendors) for (const cookie of vendor.cookies) if (granted) kept.push(matcher(cookie.name));
443
+ else if (cookie.domain === void 0) revoked.push(cookie);
444
+ }
445
+ if (revoked.length === 0) return;
446
+ const isKept = (actual) => kept.some((matches) => matches(actual));
447
+ const cleared = (cookie, actual) => options.onClear?.(cookie, actual);
448
+ for (const cookie of revoked) {
449
+ const matches = matcher(cookie.name);
450
+ const type = cookie.type ?? "http";
451
+ if (type === "http") for (const actual of cookieNames(document)) {
452
+ if (!matches(actual) || isKept(actual)) continue;
453
+ expireCookie(document, actual);
454
+ if (!cookieNames(document).includes(actual)) cleared(cookie, actual);
455
+ }
456
+ else if (type === "local_storage" || type === "session_storage") {
457
+ let storage;
458
+ try {
459
+ storage = type === "local_storage" ? window.localStorage : window.sessionStorage;
460
+ } catch {
461
+ continue;
462
+ }
463
+ for (const actual of storageKeys(storage)) {
464
+ if (!matches(actual) || isKept(actual)) continue;
465
+ storage.removeItem(actual);
466
+ cleared(cookie, actual);
467
+ }
468
+ } else if (type === "indexed_db" && typeof indexedDB !== "undefined") {
469
+ if (typeof indexedDB.databases === "function") indexedDB.databases().then((databases) => {
470
+ for (const { name } of databases) {
471
+ if (!name || !matches(name) || isKept(name)) continue;
472
+ indexedDB.deleteDatabase(name);
473
+ cleared(cookie, name);
474
+ }
475
+ }).catch(() => {});
476
+ else if (!cookie.name.includes("*") && !isKept(cookie.name)) indexedDB.deleteDatabase(cookie.name);
477
+ }
478
+ }
479
+ };
480
+ clear();
481
+ return consent.subscribe(clear);
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_MAX_AGE, DEFAULT_STORAGE_KEY, REQUIRED_CATEGORY, clearRevokedCookies, createConsent, isConsentCategoryId, unblockScripts };
557
+
558
+ //# sourceMappingURL=index.mjs.map