@luwiostack/cookie-consent 0.1.0 → 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 CHANGED
@@ -1,4 +1,4 @@
1
- import { i as isConsentCategoryId, n as CONSENT_CATEGORIES, r as REQUIRED_CATEGORY, t as ConsentError } from "./errors-D2ZIcEYK.mjs";
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
2
  import { t as usedVendors } from "./used-vendors-Dxk4PZtY.mjs";
3
3
  import { localStore } from "@luwiostack/storage";
4
4
  //#region src/domain/consent-decision.ts
@@ -82,8 +82,10 @@ function validateVendor(vendor, listedIn) {
82
82
  if (typeof vendor?.id !== "string" || vendor.id === "") throw new ConsentError(`Category "${listedIn}": a vendor id must be non-empty.`);
83
83
  const where = `Vendor "${vendor.id}"`;
84
84
  if (!Array.isArray(vendor.cookies)) throw new ConsentError(`${where}: cookies must be an array.`);
85
+ validateTransfers(vendor.transfers, where);
85
86
  const names = /* @__PURE__ */ new Set();
86
87
  for (const cookie of vendor.cookies) {
88
+ if (typeof cookie !== "object" || cookie === null) throw new ConsentError(`${where}: every cookie must be an object.`);
87
89
  if (typeof cookie.name !== "string" || cookie.name === "") throw new ConsentError(`${where}: a cookie name must be non-empty.`);
88
90
  if (names.has(cookie.name)) throw new ConsentError(`${where}: duplicate cookie "${cookie.name}".`);
89
91
  names.add(cookie.name);
@@ -91,6 +93,29 @@ function validateVendor(vendor, listedIn) {
91
93
  if (cookie.type !== void 0 && !COOKIE_TYPES.has(cookie.type)) throw new ConsentError(`${where}: cookie "${cookie.name}" has an unknown type "${cookie.type}".`);
92
94
  const { max_age } = cookie;
93
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(", ")}.`);
94
119
  }
95
120
  }
96
121
  /**
@@ -102,14 +127,19 @@ function resolveVendors(config) {
102
127
  if (typeof config !== "object" || config === null || Array.isArray(config)) throw new ConsentError("categories must be an object of category id → vendors.");
103
128
  for (const key of Object.keys(config)) if (!isConsentCategoryId(key)) throw new ConsentError(`Unknown consent category "${key}" — use ${CONSENT_CATEGORIES.join(", ")}.`);
104
129
  const merged = /* @__PURE__ */ new Map();
130
+ const idByMachineName = /* @__PURE__ */ new Map();
105
131
  const listed = Object.fromEntries(CONSENT_CATEGORIES.map((id) => [id, []]));
106
132
  for (const category of CONSENT_CATEGORIES) {
107
133
  const inCategory = config[category];
108
134
  if (inCategory === void 0) continue;
109
135
  if (!Array.isArray(inCategory)) throw new ConsentError(`Category "${category}": vendors must be an array.`);
110
136
  const seen = /* @__PURE__ */ new Set();
111
- for (const vendor of inCategory) {
112
- validateVendor(vendor, category);
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);
113
143
  const where = `Category "${category}", vendor "${vendor.id}"`;
114
144
  if (seen.has(vendor.id)) throw new ConsentError(`${where}: duplicate vendor.`);
115
145
  seen.add(vendor.id);
@@ -119,18 +149,42 @@ function resolveVendors(config) {
119
149
  vendor,
120
150
  cookies: /* @__PURE__ */ new Map()
121
151
  };
122
- for (const cookie of vendor.cookies) if (cookie.category === category || cookie.category === "necessary") entry.cookies.set(cookie.name, cookie);
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
+ }
123
161
  merged.set(vendor.id, entry);
124
162
  }
125
163
  }
126
164
  return {
127
- vendors: [...merged.values()].map(({ vendor, cookies }) => ({
128
- ...vendor,
129
- cookies: vendor.cookies.filter((c) => cookies.has(c.name))
130
- })),
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
+ }),
131
174
  listed
132
175
  };
133
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
+ }
134
188
  function reusableId(record) {
135
189
  const id = record?.consent_id;
136
190
  return typeof id === "string" && id !== "" ? id : null;
@@ -172,6 +226,8 @@ function createConsent(config = {}) {
172
226
  const ids = [.../* @__PURE__ */ new Set([...listed[id], ...vendors.map((v) => v.id)])];
173
227
  return {
174
228
  id,
229
+ machine_name: categoryMachineName(id),
230
+ description_machine_name: `${categoryMachineName(id)}_description`,
175
231
  required: id === REQUIRED_CATEGORY,
176
232
  vendors: ids.flatMap((vendorId) => {
177
233
  const vendor = byId.get(vendorId);
@@ -186,7 +242,9 @@ function createConsent(config = {}) {
186
242
  const usedIn = usedVendors(categories);
187
243
  const maxAge = config.maxAge ?? 31536e6;
188
244
  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);
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);
190
248
  const store = config.store ?? localStore("luwio.consent", { onError: "ignore" });
191
249
  const now = config.now ?? Date.now;
192
250
  let unsaved;
@@ -245,7 +303,7 @@ function createConsent(config = {}) {
245
303
  return next;
246
304
  }
247
305
  const isRequired = (id) => id === REQUIRED_CATEGORY;
248
- const isGranted = (id, vendorId) => (vendorId === void 0 || usedIn[id].has(vendorId)) && (isRequired(id) || (current()?.isGranted(id) ?? false));
306
+ const isGranted = (id, vendorId) => (vendorId === void 0 || usedIn[id]?.has(vendorId) === true) && (isRequired(id) || (current()?.isGranted(id) ?? false));
249
307
  return {
250
308
  categories,
251
309
  vendors,
@@ -299,8 +357,8 @@ var ConsentCookieFormatter = class {
299
357
  /**
300
358
  * A cookie's lifetime in `locale`, in the largest unit that divides it evenly: 2 years, 3 months,
301
359
  * 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.
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)`.
304
362
  */
305
363
  static formatLocale(cookie, locale, options = {}) {
306
364
  const { max_age } = cookie;
@@ -367,8 +425,9 @@ function storageKeys(storage) {
367
425
  *
368
426
  * Only **first-party** storage can be reached: cookies on your own domain (tried with every parent
369
427
  * 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
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
372
431
  * running — reload the page (e.g. from `onClear`) to stop them.
373
432
  *
374
433
  * Returns a stop function. A no-op on the server.
@@ -381,7 +440,7 @@ function clearRevokedCookies(consent, options = {}) {
381
440
  for (const category of consent.categories) {
382
441
  const granted = category.id === "necessary" || consent.isGranted(category.id);
383
442
  for (const vendor of category.vendors) for (const cookie of vendor.cookies) if (granted) kept.push(matcher(cookie.name));
384
- else revoked.push(cookie);
443
+ else if (cookie.domain === void 0) revoked.push(cookie);
385
444
  }
386
445
  if (revoked.length === 0) return;
387
446
  const isKept = (actual) => kept.some((matches) => matches(actual));
@@ -413,7 +472,7 @@ function clearRevokedCookies(consent, options = {}) {
413
472
  indexedDB.deleteDatabase(name);
414
473
  cleared(cookie, name);
415
474
  }
416
- });
475
+ }).catch(() => {});
417
476
  else if (!cookie.name.includes("*") && !isKept(cookie.name)) indexedDB.deleteDatabase(cookie.name);
418
477
  }
419
478
  }
@@ -422,65 +481,6 @@ function clearRevokedCookies(consent, options = {}) {
422
481
  return consent.subscribe(clear);
423
482
  }
424
483
  //#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
484
  //#region src/integrations/unblock-scripts.ts
485
485
  /**
486
486
  * Hold third-party scripts and embeds back until their category is granted — mark them up blocked and
@@ -553,6 +553,6 @@ function unblockScripts(consent, options = {}) {
553
553
  };
554
554
  }
555
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 };
556
+ export { CONSENT_CATEGORIES, ConsentCookieFormatter, ConsentDecision, ConsentError, DEFAULT_MAX_AGE, DEFAULT_STORAGE_KEY, REQUIRED_CATEGORY, clearRevokedCookies, createConsent, isConsentCategoryId, unblockScripts };
557
557
 
558
558
  //# sourceMappingURL=index.mjs.map
@@ -1 +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,WAAW,IAAI,IAAI,MAAM,OAAO;CACvC;;CAGA,OAAO,IAAI,OAA8C;EACvD,IAAI,OAAO,MAAM,eAAe,YAAY,MAAM,eAAe,IAC/D,MAAM,IAAI,aAAa,kDAAkD;EAE3E,IAAI,OAAO,MAAM,mBAAmB,YAAY,MAAM,mBAAmB,IACvE,MAAM,IAAI,aAAa,sDAAsD;EAE/E,IAAI,OAAO,MAAM,eAAe,YAAY,CAAC,OAAO,SAAS,MAAM,UAAU,GAC3E,MAAM,IAAI,aAAa,mEAAmE;EAE5F,OAAO,IAAI,gBAAgB,KAAK;CAClC;;CAGA,OAAO,OAAO,OAAqD;EACjE,IAAI;GACF,OAAO,gBAAgB,IAAI,KAAK;EAClC,QAAQ;GACN,OAAO;EACT;CACF;;CAGA,UAAU,IAAgC;EACxC,OAAO,KAAKA,SAAS,IAAI,EAAE;CAC7B;;CAGA,UAA+B;EAC7B,OAAO,CAAC,GAAG,KAAKA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,SAAS,OAAO,qBAAqB,aAAa;EACxE,WAAW,IAAI,kBAAkB,YAAY;GAC3C,IAAI,QAAQ,MAAM,MAAM,EAAE,WAAW,SAAS,CAAC,GAAG,SAAS;EAC7D,CAAC;EACD,MAAM,SAAS,gBAAgB,WAAW,KAAK,kBAAmB;EAClE,SAAS,QAAQ,QAAQ;GAAE,WAAW;GAAM,SAAS;EAAK,CAAC;CAC7D;CAEA,aAAa;EACX,YAAY;EACZ,UAAU,WAAW;CACvB;AACF"}
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/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 { categoryMachineName, toConsentVendor } from './machine-names'\nimport type {\n ConsentCategoriesConfig,\n ConsentCategory,\n ConsentConfig,\n ConsentCookie,\n ConsentCookieDeclaration,\n ConsentCookieType,\n ConsentManager,\n ConsentSnapshot,\n ConsentTransferDeclaration,\n ConsentTransferSafeguard,\n ConsentVendor,\n ConsentVendorDeclaration,\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: ConsentVendorDeclaration, 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 validateTransfers(vendor.transfers, where)\n const names = new Set<string>()\n for (const cookie of vendor.cookies as unknown[] as ConsentCookieDeclaration[]) {\n if (typeof cookie !== 'object' || cookie === null) {\n throw new ConsentError(`${where}: every cookie must be an object.`)\n }\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 if (\n cookie.domain !== undefined &&\n (typeof cookie.domain !== 'string' || !DOMAIN.test(cookie.domain))\n ) {\n throw new ConsentError(\n `${where}: cookie \"${cookie.name}\" needs domain as a host name like \".youtube.com\", or none for the site's own domain.`,\n )\n }\n }\n}\n\n/** A cookie domain: a host name, optionally with a leading dot, no scheme, port or path. */\nconst DOMAIN = /^\\.?[a-z0-9-]+(\\.[a-z0-9-]+)+$/i\n\nconst SAFEGUARDS: ReadonlySet<ConsentTransferSafeguard> = new Set(['adequacy', 'dpf', 'scc', 'bcr'])\n\n/** Transfers: absent, or per unique ISO alpha-2 country at least one known safeguard. */\nfunction validateTransfers(transfers: unknown, where: string): void {\n if (transfers === undefined) return\n if (!Array.isArray(transfers)) throw new ConsentError(`${where}: transfers must be an array.`)\n const countries = new Set<string>()\n for (const transfer of transfers as ConsentTransferDeclaration[]) {\n const country = transfer?.country\n if (typeof country !== 'string' || !/^[A-Z]{2}$/.test(country)) {\n throw new ConsentError(`${where}: a transfer needs country as ISO alpha-2, e.g. \"US\".`)\n }\n if (countries.has(country)) throw new ConsentError(`${where}: duplicate transfer \"${country}\".`)\n countries.add(country)\n const { safeguards } = transfer\n if (\n !Array.isArray(safeguards) ||\n safeguards.length === 0 ||\n !safeguards.every((s) => SAFEGUARDS.has(s))\n ) {\n throw new ConsentError(\n `${where}: transfer \"${country}\" needs safeguards from ${[...SAFEGUARDS].join(', ')}.`,\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 // Two ids may not share a machine name: their translation keys would collide.\n const idByMachineName = new Map<string, string>()\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 declaration of inCategory) {\n validateVendor(declaration, category)\n const vendor = toConsentVendor(declaration)\n const other = idByMachineName.get(vendor.machine_name)\n if (other !== undefined && other !== vendor.id) {\n throw new ConsentError(\n `Vendors \"${other}\" and \"${vendor.id}\" have the same machine name \"${vendor.machine_name}\".`,\n )\n }\n idByMachineName.set(vendor.machine_name, vendor.id)\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 if (entry.vendor !== vendor && !sameVendorInfo(entry.vendor, vendor)) {\n throw new ConsentError(\n `Vendor \"${vendor.id}\" is declared differently in two categories (privacy_policy_url or transfers).`,\n )\n }\n // Each listing may declare its own cookies (a preset narrowed per category): the vendor gets\n // the union. The same cookie declared twice must be declared the same way.\n for (const cookie of vendor.cookies) {\n if (cookie.category !== category && cookie.category !== REQUIRED_CATEGORY) continue\n const known = entry.cookies.get(cookie.name)\n if (known !== undefined && !sameCookie(known, cookie)) {\n throw new ConsentError(\n `Vendor \"${vendor.id}\": cookie \"${cookie.name}\" is declared differently in two categories.`,\n )\n }\n // Two names from different listings may not share a translation key (one declaration is\n // already checked by toConsentVendor).\n const clash = [...entry.cookies.values()].find(\n (c) => c.name !== cookie.name && c.machine_name === cookie.machine_name,\n )\n if (clash) {\n throw new ConsentError(\n `Vendor \"${vendor.id}\": cookies \"${clash.name}\" and \"${cookie.name}\" have the same machine name \"${cookie.machine_name}\".`,\n )\n }\n entry.cookies.set(cookie.name, cookie)\n }\n merged.set(vendor.id, entry)\n }\n }\n const vendors = [...merged.values()].map(({ vendor, cookies }) => {\n // The first declaration's cookie order, then what later listings added — always the\n // declaration that brought the cookie in (the first one may declare it for another category).\n const order = vendor.cookies.map((c) => c.name).filter((name) => cookies.has(name))\n const ordered = new Set(order)\n for (const name of cookies.keys()) if (!ordered.has(name)) order.push(name)\n return {\n ...vendor,\n cookies: order.flatMap((name) => cookies.get(name) ?? []),\n }\n })\n return { vendors, listed }\n}\n\nfunction sameVendorInfo(a: ConsentVendorDeclaration, b: ConsentVendorDeclaration): boolean {\n return (\n a.privacy_policy_url === b.privacy_policy_url &&\n transfersKey(a.transfers) === transfersKey(b.transfers)\n )\n}\n\n/** Transfers in a canonical form: the same countries and safeguards in any order compare equal. */\nfunction transfersKey(transfers: readonly ConsentTransferDeclaration[] | undefined): string {\n if (transfers === undefined) return 'none'\n return transfers\n .map((t) => `${t.country}:${[...t.safeguards].sort().join(',')}`)\n .sort()\n .join(';')\n}\n\nfunction sameCookie(a: ConsentCookieDeclaration, b: ConsentCookieDeclaration): boolean {\n return (\n a.category === b.category &&\n (a.type ?? 'http') === (b.type ?? 'http') &&\n a.max_age === b.max_age &&\n a.domain === b.domain\n )\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 machine_name: categoryMachineName(id),\n description_machine_name: `${categoryMachineName(id)}_description`,\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 rawVersion: unknown = config.policyVersion ?? 1\n const validVersion =\n (typeof rawVersion === 'string' && rawVersion !== '') ||\n (typeof rawVersion === 'number' && Number.isFinite(rawVersion))\n if (!validVersion) {\n throw new ConsentError('policyVersion must be a non-empty string or a finite number.')\n }\n const policyVersion = String(rawVersion)\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 // An unknown category (untyped input: a data-consent attribute) is never granted.\n (vendorId === undefined || usedIn[id]?.has(vendorId) === true) &&\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 translate\n * them — `formatLocale(cookie, locale) ?? t(cookie.max_age_machine_name)`.\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 (declared with a `domain`, like `IDE` on\n * doubleclick.net) lives on another site: it's skipped, so a first-party item that shares its name\n * is never removed. `HttpOnly` cookies can only be removed 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 // A third-party cookie (one with a domain) lives on the vendor's domain: out of reach, and\n // a first-party item that happens to share its name is not ours to remove.\n else if (cookie.domain === undefined) 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\n .databases()\n .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 .catch(() => {}) // Listing refused (a privacy mode): nothing to remove.\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\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,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S,QAAQ,QAAQ;GAAE,WAAW;GAAM,SAAS;EAAK,CAAC;CAC7D;CAEA,aAAa;EACX,YAAY;EACZ,UAAU,WAAW;CACvB;AACF"}
@@ -0,0 +1,102 @@
1
+ //#region src/categories.ts
2
+ /**
3
+ * The fixed consent categories, in display order — the same four every consent tool (and Google
4
+ * Consent Mode) works with. `necessary` is always granted. A category's name and description are
5
+ * translated by machine name (`consent_category_<id>`, `consent_category_<id>_description`) from
6
+ * the package catalogs.
7
+ */
8
+ const CONSENT_CATEGORIES = [
9
+ "necessary",
10
+ "preferences",
11
+ "statistics",
12
+ "marketing"
13
+ ];
14
+ /** The category that is always granted and can't be refused. */
15
+ const REQUIRED_CATEGORY = "necessary";
16
+ /** Whether a value is one of the fixed category ids. */
17
+ function isConsentCategoryId(value) {
18
+ return CONSENT_CATEGORIES.includes(value);
19
+ }
20
+ //#endregion
21
+ //#region src/errors.ts
22
+ /** Thrown for an invalid consent configuration or an invalid stored decision. */
23
+ var ConsentError = class extends Error {
24
+ constructor(message) {
25
+ super(message);
26
+ this.name = "ConsentError";
27
+ }
28
+ };
29
+ //#endregion
30
+ //#region src/utils/to-machine-name.ts
31
+ /**
32
+ * Converts a human-readable name to a stable snake_case machine name.
33
+ *
34
+ * - Normalizes Unicode (NFD) and strips diacritics (é → e, ñ → n, …)
35
+ * - Lowercases
36
+ * - Replaces any run of non-alphanumeric characters with a single underscore
37
+ * - Trims leading/trailing underscores
38
+ */
39
+ function toMachineName(name) {
40
+ return name.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
41
+ }
42
+ //#endregion
43
+ //#region src/machine-names.ts
44
+ /** @internal A category's name key, e.g. `consent_category_statistics`. */
45
+ const categoryMachineName = (id) => `consent_category_${id}`;
46
+ /** @internal A cookie type's key, e.g. `consent_cookie_type_local_storage`. */
47
+ const cookieTypeMachineName = (type) => `consent_cookie_type_${type}`;
48
+ /** @internal A worded lifetime's key: `consent_max_age_session` / `consent_max_age_persistent`. */
49
+ const maxAgeMachineName = (maxAge) => `consent_max_age_${maxAge}`;
50
+ /** @internal A cookie party's key: `consent_cookie_party_first` / `consent_cookie_party_third`. */
51
+ const partyMachineName = (party) => `consent_cookie_party_${party}`;
52
+ /** @internal A transfer safeguard's key, e.g. `consent_transfer_safeguard_dpf`. */
53
+ const safeguardMachineName = (safeguard) => `consent_transfer_safeguard_${safeguard}`;
54
+ /**
55
+ * @internal A cookie's key: its vendor's machine name plus its name, a `*` read as `wildcard` —
56
+ * `google_analytics` + `_ga_*` → `google_analytics_ga_wildcard`.
57
+ */
58
+ function cookieMachineName(vendor, cookieName) {
59
+ const name = toMachineName(cookieName.replaceAll("*", " wildcard "));
60
+ return name === "" ? "" : `${vendor}_${name}`;
61
+ }
62
+ /**
63
+ * @internal A vendor declaration with its machine names, cookies included. Throws when its id or a
64
+ * cookie name has no letters or digits, or when two cookie names come out the same.
65
+ */
66
+ function toConsentVendor(declaration) {
67
+ const where = `Vendor "${declaration.id}"`;
68
+ const machine_name = toMachineName(declaration.id);
69
+ if (machine_name === "") throw new ConsentError(`${where}: the id needs letters or digits for its machine name.`);
70
+ const byMachineName = /* @__PURE__ */ new Map();
71
+ const cookies = declaration.cookies.map((cookie) => {
72
+ const key = cookieMachineName(machine_name, cookie.name);
73
+ if (key === "") throw new ConsentError(`${where}: cookie "${cookie.name}" needs letters or digits.`);
74
+ const clash = byMachineName.get(key);
75
+ if (clash !== void 0 && clash !== cookie.name) throw new ConsentError(`${where}: cookies "${clash}" and "${cookie.name}" have the same machine name "${key}".`);
76
+ byMachineName.set(key, cookie.name);
77
+ const party = cookie.domain === void 0 ? "first" : "third";
78
+ return {
79
+ ...cookie,
80
+ machine_name: key,
81
+ type_machine_name: cookieTypeMachineName(cookie.type ?? "http"),
82
+ party,
83
+ party_machine_name: partyMachineName(party),
84
+ ...typeof cookie.max_age === "string" ? { max_age_machine_name: maxAgeMachineName(cookie.max_age) } : {}
85
+ };
86
+ });
87
+ const { transfers: declared, ...rest } = declaration;
88
+ const transfers = declared?.map((transfer) => ({
89
+ ...transfer,
90
+ safeguard_machine_names: transfer.safeguards.map(safeguardMachineName)
91
+ }));
92
+ return {
93
+ ...rest,
94
+ machine_name,
95
+ ...transfers !== void 0 ? { transfers } : {},
96
+ cookies
97
+ };
98
+ }
99
+ //#endregion
100
+ export { REQUIRED_CATEGORY as a, CONSENT_CATEGORIES as i, toConsentVendor as n, isConsentCategoryId as o, ConsentError as r, categoryMachineName as t };
101
+
102
+ //# sourceMappingURL=machine-names-DAJioLt5.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"machine-names-DAJioLt5.mjs","names":[],"sources":["../src/categories.ts","../src/errors.ts","../src/utils/to-machine-name.ts","../src/machine-names.ts"],"sourcesContent":["/**\n * The fixed consent categories, in display order — the same four every consent tool (and Google\n * Consent Mode) works with. `necessary` is always granted. A category's name and description are\n * translated by machine name (`consent_category_<id>`, `consent_category_<id>_description`) from\n * the package catalogs.\n */\nexport const CONSENT_CATEGORIES = ['necessary', 'preferences', 'statistics', 'marketing'] as const\n\n/** `'necessary' | 'preferences' | 'statistics' | 'marketing'` */\nexport type ConsentCategoryId = (typeof CONSENT_CATEGORIES)[number]\n\n/** The category that is always granted and can't be refused. */\nexport const REQUIRED_CATEGORY = 'necessary' satisfies ConsentCategoryId\n\n/** Whether a value is one of the fixed category ids. */\nexport function isConsentCategoryId(value: unknown): value is ConsentCategoryId {\n return (CONSENT_CATEGORIES as readonly unknown[]).includes(value)\n}\n","/** Thrown for an invalid consent configuration or an invalid stored decision. */\nexport class ConsentError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ConsentError'\n }\n}\n","/**\n * Converts a human-readable name to a stable snake_case machine name.\n *\n * - Normalizes Unicode (NFD) and strips diacritics (é → e, ñ → n, …)\n * - Lowercases\n * - Replaces any run of non-alphanumeric characters with a single underscore\n * - Trims leading/trailing underscores\n */\nexport function toMachineName(name: string): string {\n return name\n .normalize('NFD')\n .replace(/\\p{M}/gu, '') // strip combining marks (diacritics)\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_') // non-alphanumeric runs → _\n .replace(/^_|_$/g, '') // trim edges\n}\n","import type { ConsentCategoryId } from './categories'\nimport { ConsentError } from './errors'\nimport type {\n ConsentCookie,\n ConsentCookieParty,\n ConsentCookieType,\n ConsentCookieWordedMaxAge,\n ConsentTransferSafeguard,\n ConsentVendor,\n ConsentVendorDeclaration,\n} from './types'\nimport { toMachineName } from './utils/to-machine-name'\n\n// Every text a cookie list needs has one translation key: a snake_case machine name, like a\n// country's. The categories and the generic words carry a `consent_` prefix, so they can't clash\n// with the app's own keys; a vendor's is its id, a cookie's is its vendor's plus its name.\n\n/** @internal A category's name key, e.g. `consent_category_statistics`. */\nexport const categoryMachineName = (id: ConsentCategoryId) => `consent_category_${id}`\n\n/** @internal A cookie type's key, e.g. `consent_cookie_type_local_storage`. */\nexport const cookieTypeMachineName = (type: ConsentCookieType) => `consent_cookie_type_${type}`\n\n/** @internal A worded lifetime's key: `consent_max_age_session` / `consent_max_age_persistent`. */\nexport const maxAgeMachineName = (maxAge: ConsentCookieWordedMaxAge) => `consent_max_age_${maxAge}`\n\n/** @internal A cookie party's key: `consent_cookie_party_first` / `consent_cookie_party_third`. */\nexport const partyMachineName = (party: ConsentCookieParty) => `consent_cookie_party_${party}`\n\n/** @internal A transfer safeguard's key, e.g. `consent_transfer_safeguard_dpf`. */\nexport const safeguardMachineName = (safeguard: ConsentTransferSafeguard) =>\n `consent_transfer_safeguard_${safeguard}`\n\n/**\n * @internal A cookie's key: its vendor's machine name plus its name, a `*` read as `wildcard` —\n * `google_analytics` + `_ga_*` → `google_analytics_ga_wildcard`.\n */\nexport function cookieMachineName(vendor: string, cookieName: string): string {\n const name = toMachineName(cookieName.replaceAll('*', ' wildcard '))\n return name === '' ? '' : `${vendor}_${name}`\n}\n\n/**\n * @internal A vendor declaration with its machine names, cookies included. Throws when its id or a\n * cookie name has no letters or digits, or when two cookie names come out the same.\n */\nexport function toConsentVendor(declaration: ConsentVendorDeclaration): ConsentVendor {\n const where = `Vendor \"${declaration.id}\"`\n const machine_name = toMachineName(declaration.id)\n if (machine_name === '') {\n throw new ConsentError(`${where}: the id needs letters or digits for its machine name.`)\n }\n const byMachineName = new Map<string, string>()\n const cookies: ConsentCookie[] = declaration.cookies.map((cookie) => {\n const key = cookieMachineName(machine_name, cookie.name)\n if (key === '') {\n throw new ConsentError(`${where}: cookie \"${cookie.name}\" needs letters or digits.`)\n }\n const clash = byMachineName.get(key)\n if (clash !== undefined && clash !== cookie.name) {\n throw new ConsentError(\n `${where}: cookies \"${clash}\" and \"${cookie.name}\" have the same machine name \"${key}\".`,\n )\n }\n byMachineName.set(key, cookie.name)\n const party: ConsentCookieParty = cookie.domain === undefined ? 'first' : 'third'\n return {\n ...cookie,\n machine_name: key,\n type_machine_name: cookieTypeMachineName(cookie.type ?? 'http'),\n party,\n party_machine_name: partyMachineName(party),\n ...(typeof cookie.max_age === 'string'\n ? { max_age_machine_name: maxAgeMachineName(cookie.max_age) }\n : {}),\n }\n })\n const { transfers: declared, ...rest } = declaration\n const transfers = declared?.map((transfer) => ({\n ...transfer,\n safeguard_machine_names: transfer.safeguards.map(safeguardMachineName),\n }))\n return {\n ...rest,\n machine_name,\n ...(transfers !== undefined ? { transfers } : {}),\n cookies,\n }\n}\n"],"mappings":";;;;;;;AAMA,MAAa,qBAAqB;CAAC;CAAa;CAAe;CAAc;AAAW;;AAMxF,MAAa,oBAAoB;;AAGjC,SAAgB,oBAAoB,OAA4C;CAC9E,OAAQ,mBAA0C,SAAS,KAAK;AAClE;;;;AChBA,IAAa,eAAb,cAAkC,MAAM;CACtC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;;;;;;;;ACEA,SAAgB,cAAc,MAAsB;CAClD,OAAO,KACJ,UAAU,KAAK,CAAC,CAChB,QAAQ,WAAW,EAAE,CAAC,CACtB,YAAY,CAAC,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