@luwiostack/cookie-consent 0.2.0 → 0.3.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.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as REQUIRED_CATEGORY, S as ConsentCategoryId, _ as ConsentVendorDeclaration, a as ConsentCookieDeclaration, b as ConsentDecisionInput, c as ConsentCookieType, d as ConsentSnapshot, f as ConsentStatus, g as ConsentVendor, h as ConsentTransferSafeguard, i as ConsentCookie, l as ConsentCookieWordedMaxAge, m as ConsentTransferDeclaration, n as ConsentCategory, o as ConsentCookieMaxAge, p as ConsentTransfer, r as ConsentConfig, s as ConsentCookieParty, t as ConsentCategoriesConfig, u as ConsentManager, v as StoredConsent, w as isConsentCategoryId, x as CONSENT_CATEGORIES, y as ConsentDecision } from "./types-ByyibBUg.mjs";
1
+ import { C as REQUIRED_CATEGORY, S as ConsentCategoryId, _ as ConsentVendorDeclaration, a as ConsentCookieDeclaration, b as ConsentDecisionInput, c as ConsentCookieType, d as ConsentSnapshot, f as ConsentStatus, g as ConsentVendor, h as ConsentTransferSafeguard, i as ConsentCookie, l as ConsentCookieWordedMaxAge, m as ConsentTransferDeclaration, n as ConsentCategory, o as ConsentCookieMaxAge, p as ConsentTransfer, r as ConsentConfig, s as ConsentCookieParty, t as ConsentCategoriesConfig, u as ConsentManager, v as StoredConsent, w as isConsentCategoryId, x as CONSENT_CATEGORIES, y as ConsentDecision } from "./types-WpJKTgRa.mjs";
2
2
  //#region src/consent.d.ts
3
3
  /** The key the default `localStorage` store keeps the decision behind. */
4
4
  declare const DEFAULT_STORAGE_KEY = "luwio.consent";
@@ -109,7 +109,9 @@ interface UnblockScriptsOptions {
109
109
  * ```
110
110
  *
111
111
  * A script is replaced by a fresh `<script>` copy (the only way to make the browser run it), its
112
- * CSP `nonce` included; an embed gets its `src` from `data-src`. Activation is one-way: a revoked category can't un-run a
112
+ * CSP `nonce` included. Scripts run in document order, as the parser would run them: consecutive
113
+ * external ones download in parallel and run in order, and an inline one waits until every external script above it
114
+ * has loaded (or failed). An `async` script holds nothing up. An embed gets its `src` from `data-src`. Activation is one-way: a revoked category can't un-run a
113
115
  * script — reload the page from `onChange` when something is withdrawn. Returns a stop function.
114
116
  */
115
117
  declare function unblockScripts(consent: ConsentManager, options?: UnblockScriptsOptions): () => void;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/consent.ts","../src/errors.ts","../src/formatters/consent-cookie-formatter.ts","../src/integrations/clear-revoked-cookies.ts","../src/integrations/unblock-scripts.ts"],"mappings":";;;cA4Ba;;cAEA;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgQG,cAAc,SAAQ,gBAAqB;;;;cC7R9C,qBAAqB;EAChC,YAAY;;;;UCAG;;EAEf;;;cAoBW;;;;;;;SAOJ,aACL,QAAQ,KAAK,2BACb,QAAQ,KAAK,QACb,UAAS;;;;UC/BI;;;;;EAKf,WAAW,QAAQ,eAAe;;;;;;;;;;;;;;;;;iBAyEpB,oBACd,SAAS,gBACT,UAAS;;;UChFM;;EAEf,OAAO;;EAEP;;;;;EAKA;;EAEA;;;;;;;;;;;;;;;;;;;;;;iBAuBc,eACd,SAAS,gBACT,UAAS"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/consent.ts","../src/errors.ts","../src/formatters/consent-cookie-formatter.ts","../src/integrations/clear-revoked-cookies.ts","../src/integrations/unblock-scripts.ts"],"mappings":";;;cA4Ba;;cAEA;;;;;;;;;;;;;;;;;;;;;;;;;;iBAwRG,cAAc,SAAQ,gBAAqB;;;;cCrT9C,qBAAqB;EAChC,YAAY;;;;UCAG;;EAEf;;;cAoBW;;;;;;;SAOJ,aACL,QAAQ,KAAK,2BACb,QAAQ,KAAK,QACb,UAAS;;;;UC/BI;;;;;EAKf,WAAW,QAAQ,eAAe;;;;;;;;;;;;;;;;;iBAgGpB,oBACd,SAAS,gBACT,UAAS;;;UCvGM;;EAEf,OAAO;;EAEP;;;;;EAKA;;EAEA;;;;;;;;;;;;;;;;;;;;;;;;iBA6Dc,eACd,SAAS,gBACT,UAAS"}
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
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";
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-DX8eCM2Q.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
@@ -161,19 +161,41 @@ function resolveVendors(config) {
161
161
  merged.set(vendor.id, entry);
162
162
  }
163
163
  }
164
+ const vendors = [...merged.values()].map(({ vendor, cookies }) => {
165
+ const order = vendor.cookies.map((c) => c.name).filter((name) => cookies.has(name));
166
+ const ordered = new Set(order);
167
+ for (const name of cookies.keys()) if (!ordered.has(name)) order.push(name);
168
+ return {
169
+ ...vendor,
170
+ cookies: order.flatMap((name) => cookies.get(name) ?? [])
171
+ };
172
+ });
173
+ rejectSharedMachineNames(vendors);
164
174
  return {
165
- vendors: [...merged.values()].map(({ vendor, cookies }) => {
166
- const order = vendor.cookies.map((c) => c.name).filter((name) => cookies.has(name));
167
- const ordered = new Set(order);
168
- for (const name of cookies.keys()) if (!ordered.has(name)) order.push(name);
169
- return {
170
- ...vendor,
171
- cookies: order.flatMap((name) => cookies.get(name) ?? [])
172
- };
173
- }),
175
+ vendors,
174
176
  listed
175
177
  };
176
178
  }
179
+ /**
180
+ * Every vendor and cookie key must name one thing: `google` + cookie `analytics` comes out
181
+ * `google_analytics`, the key of the Google Analytics vendor — both would render the same text.
182
+ * (Within one vendor, and between vendor ids, this is already checked as they're declared.)
183
+ */
184
+ function rejectSharedMachineNames(vendors) {
185
+ const owners = /* @__PURE__ */ new Map();
186
+ const claim = (key, owner) => {
187
+ const other = owners.get(key);
188
+ if (other !== void 0 && other !== owner) {
189
+ const first = other.charAt(0).toUpperCase() + other.slice(1);
190
+ throw new ConsentError(`${first} and ${owner} have the same machine name "${key}".`);
191
+ }
192
+ owners.set(key, owner);
193
+ };
194
+ for (const vendor of vendors) {
195
+ claim(vendor.machine_name, `vendor "${vendor.id}"`);
196
+ for (const cookie of vendor.cookies) claim(cookie.machine_name, `vendor "${vendor.id}" cookie "${cookie.name}"`);
197
+ }
198
+ }
177
199
  function sameVendorInfo(a, b) {
178
200
  return a.privacy_policy_url === b.privacy_policy_url && transfersKey(a.transfers) === transfersKey(b.transfers);
179
201
  }
@@ -248,11 +270,18 @@ function createConsent(config = {}) {
248
270
  const store = config.store ?? localStore("luwio.consent", { onError: "ignore" });
249
271
  const now = config.now ?? Date.now;
250
272
  let unsaved;
273
+ let unsavedOver = null;
251
274
  const listeners = /* @__PURE__ */ new Set();
252
275
  const notify = () => {
253
276
  for (const fn of [...listeners]) fn();
254
277
  };
255
- const read = () => unsaved !== void 0 ? unsaved : store.read();
278
+ const read = () => {
279
+ const stored = store.read();
280
+ if (unsaved === void 0) return stored;
281
+ if (stored === unsavedOver) return unsaved;
282
+ unsaved = void 0;
283
+ return stored;
284
+ };
256
285
  let lastRecord;
257
286
  let lastExpired = false;
258
287
  let lastSnapshot = PENDING;
@@ -294,10 +323,20 @@ function createConsent(config = {}) {
294
323
  decided_at: now()
295
324
  });
296
325
  const record = next.toJSON();
297
- store.write(record);
326
+ const before = store.read();
327
+ let announced = false;
328
+ const stopWatching = store.subscribe(() => {
329
+ announced = true;
330
+ });
331
+ try {
332
+ store.write(record);
333
+ } finally {
334
+ stopWatching();
335
+ }
298
336
  const kept = store.read();
299
- const landed = kept?.consent_id === record.consent_id && kept?.decided_at === record.decided_at;
337
+ const landed = announced || kept !== before;
300
338
  unsaved = landed ? void 0 : record;
339
+ unsavedOver = kept;
301
340
  if (!landed) notify();
302
341
  config.onChange?.(next, previous);
303
342
  return next;
@@ -310,10 +349,11 @@ function createConsent(config = {}) {
310
349
  policyVersion,
311
350
  getSnapshot,
312
351
  subscribe: (onChange) => {
313
- listeners.add(onChange);
314
- const unsubscribe = store.subscribe(onChange);
352
+ const listener = () => onChange();
353
+ listeners.add(listener);
354
+ const unsubscribe = store.subscribe(listener);
315
355
  return () => {
316
- listeners.delete(onChange);
356
+ listeners.delete(listener);
317
357
  unsubscribe();
318
358
  };
319
359
  },
@@ -395,19 +435,36 @@ function domainCandidates(hostname) {
395
435
  for (let i = 0; i < parts.length - 1; i++) parents.push(parts.slice(i).join("."));
396
436
  return [void 0, ...parents];
397
437
  }
398
- /** The paths a cookie may have been set for, from this page up to the root: `/a/b` → `/a/b`, `/a`, `/`. @internal */
438
+ /**
439
+ * The paths a cookie may have been set for, from the root down to this page — each parent with and
440
+ * without a trailing `/` (`Path=/a/` is sent on `/a/b` too): `/a/b` → `/`, `/a`, `/a/`, `/a/b`. The
441
+ * page's own path gets its `/` variant only when the URL has one.
442
+ * @internal
443
+ */
399
444
  function pathCandidates(pathname) {
400
445
  const segments = pathname.split("/").filter(Boolean);
401
446
  const paths = ["/"];
402
- for (let i = 1; i <= segments.length; i++) paths.push(`/${segments.slice(0, i).join("/")}`);
447
+ for (let i = 1; i <= segments.length; i++) {
448
+ const path = `/${segments.slice(0, i).join("/")}`;
449
+ paths.push(path);
450
+ if (i < segments.length || pathname.endsWith("/")) paths.push(`${path}/`);
451
+ }
403
452
  return paths;
404
453
  }
405
454
  function cookieNames(doc) {
406
455
  return doc.cookie.split(";").map((pair) => pair.slice(0, pair.indexOf("=") === -1 ? void 0 : pair.indexOf("=")).trim()).filter(Boolean);
407
456
  }
408
457
  function expireCookie(doc, name) {
409
- const { hostname, pathname } = doc.location;
410
- for (const domain of domainCandidates(hostname)) for (const path of pathCandidates(pathname)) doc.cookie = `${name}=; Path=${path}${domain ? `; Domain=${domain}` : ""}; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`;
458
+ const { hostname, pathname, protocol } = doc.location;
459
+ const variants = !(doc.defaultView?.isSecureContext ?? protocol === "https:") ? [""] : protocol === "https:" ? ["; Secure"] : ["", "; Secure"];
460
+ const expired = "Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT";
461
+ for (const secure of variants) {
462
+ if (name.startsWith("__Host-")) {
463
+ doc.cookie = `${name}=; Path=/${secure}; ${expired}`;
464
+ continue;
465
+ }
466
+ for (const domain of domainCandidates(hostname)) for (const path of pathCandidates(pathname)) doc.cookie = `${name}=; Path=${path}${domain ? `; Domain=${domain}` : ""}${secure}; ${expired}`;
467
+ }
411
468
  }
412
469
  function storageKeys(storage) {
413
470
  const keys = [];
@@ -482,6 +539,31 @@ function clearRevokedCookies(consent, options = {}) {
482
539
  }
483
540
  //#endregion
484
541
  //#region src/integrations/unblock-scripts.ts
542
+ const loading = /* @__PURE__ */ new Set();
543
+ /** A script still loading in `doc` (one taken out of the page holds nothing up, and is forgotten). */
544
+ function loadingIn(doc) {
545
+ for (const script of loading) if (!script.isConnected) loading.delete(script);
546
+ else if (script.ownerDocument === doc) return script;
547
+ }
548
+ /** Call `fn` once when `script` has loaded or failed. */
549
+ function onSettled(script, fn) {
550
+ script.addEventListener("load", fn, { once: true });
551
+ script.addEventListener("error", fn, { once: true });
552
+ }
553
+ const JS_TYPE = /^(?:(?:application|text)\/(?:x-)?(?:java|ecma)script|text\/(?:jscript|livescript|javascript1\.[0-5]))$/i;
554
+ /**
555
+ * Whether an external script holds up the inline ones after it, and runs in order with the external
556
+ * ones (`async = false`): the browser fires `load` or `error` for it.
557
+ * An `async` one doesn't wait; one the browser won't run (a `nomodule` script, a type that isn't
558
+ * JavaScript) fires neither event, and waiting on it would block everything after it for good.
559
+ */
560
+ function holdsUpOthers(el, type) {
561
+ if (el.hasAttribute("async")) return false;
562
+ const t = (type ?? "").trim();
563
+ if (t.toLowerCase() === "module") return true;
564
+ if (t !== "" && !JS_TYPE.test(t)) return false;
565
+ return !el.hasAttribute("nomodule");
566
+ }
485
567
  /**
486
568
  * Hold third-party scripts and embeds back until their category is granted — mark them up blocked and
487
569
  * this activates them the moment consent allows (on load, and on every later change):
@@ -499,7 +581,9 @@ function clearRevokedCookies(consent, options = {}) {
499
581
  * ```
500
582
  *
501
583
  * A script is replaced by a fresh `<script>` copy (the only way to make the browser run it), its
502
- * CSP `nonce` included; an embed gets its `src` from `data-src`. Activation is one-way: a revoked category can't un-run a
584
+ * CSP `nonce` included. Scripts run in document order, as the parser would run them: consecutive
585
+ * external ones download in parallel and run in order, and an inline one waits until every external script above it
586
+ * has loaded (or failed). An `async` script holds nothing up. An embed gets its `src` from `data-src`. Activation is one-way: a revoked category can't un-run a
503
587
  * script — reload the page from `onChange` when something is withdrawn. Returns a stop function.
504
588
  */
505
589
  function unblockScripts(consent, options = {}) {
@@ -512,21 +596,66 @@ function unblockScripts(consent, options = {}) {
512
596
  const vendor = el.getAttribute(vendorAttr) ?? void 0;
513
597
  return ids.length > 0 && ids.every((id) => consent.isGranted(id, vendor));
514
598
  };
599
+ const queue = [];
600
+ const queued = /* @__PURE__ */ new WeakSet();
601
+ let waitingOn = null;
602
+ let stopped = false;
603
+ const insert = (el) => {
604
+ const script = document.createElement("script");
605
+ for (const { name, value } of Array.from(el.attributes)) {
606
+ if (name === "type" || name === "data-type") continue;
607
+ script.setAttribute(name, value);
608
+ }
609
+ const type = el.getAttribute("data-type");
610
+ if (type) script.setAttribute("type", type);
611
+ const { nonce } = el;
612
+ if (nonce) script.nonce = nonce;
613
+ if (!el.hasAttribute("src")) script.text = el.textContent ?? "";
614
+ else if (holdsUpOthers(el, type)) {
615
+ script.async = false;
616
+ loading.add(script);
617
+ onSettled(script, () => loading.delete(script));
618
+ }
619
+ el.replaceWith(script);
620
+ };
621
+ const waitFor = (script) => {
622
+ waitingOn = script;
623
+ onSettled(script, () => {
624
+ if (waitingOn !== script) return;
625
+ waitingOn = null;
626
+ drain();
627
+ });
628
+ };
629
+ /** A script waited on but taken out of the page never settles: stop waiting, it holds nothing up. */
630
+ const dropRemovedBlocker = () => {
631
+ if (waitingOn?.isConnected !== false) return;
632
+ waitingOn = null;
633
+ drain();
634
+ };
635
+ const drain = () => {
636
+ while (waitingOn === null && !stopped && queue.length > 0) {
637
+ const el = queue[0];
638
+ if (!el.isConnected || !allowed(el)) {
639
+ queue.shift();
640
+ queued.delete(el);
641
+ continue;
642
+ }
643
+ if (!el.hasAttribute("src")) {
644
+ const blocker = loadingIn(el.ownerDocument);
645
+ if (blocker) return waitFor(blocker);
646
+ }
647
+ queue.shift();
648
+ insert(el);
649
+ }
650
+ };
515
651
  const activate = () => {
652
+ dropRemovedBlocker();
516
653
  for (const el of Array.from(root.querySelectorAll(`script[type="text/plain"][${attr}]`))) {
517
- if (!allowed(el)) continue;
518
- const script = document.createElement("script");
519
- for (const { name, value } of Array.from(el.attributes)) {
520
- if (name === "type" || name === "data-type") continue;
521
- script.setAttribute(name, value);
522
- }
523
- const type = el.getAttribute("data-type");
524
- if (type) script.setAttribute("type", type);
525
- const { nonce } = el;
526
- if (nonce) script.nonce = nonce;
527
- if (!el.hasAttribute("src")) script.text = el.textContent ?? "";
528
- el.replaceWith(script);
654
+ if (queued.has(el) || !allowed(el)) continue;
655
+ queued.add(el);
656
+ queue.push(el);
529
657
  }
658
+ drain();
530
659
  for (const el of Array.from(root.querySelectorAll(`[${attr}][data-src]:not(script)`))) {
531
660
  if (!allowed(el)) continue;
532
661
  const src = el.getAttribute("data-src");
@@ -540,6 +669,7 @@ function unblockScripts(consent, options = {}) {
540
669
  if ((options.observe ?? true) && typeof MutationObserver !== "undefined") {
541
670
  observer = new MutationObserver((records) => {
542
671
  if (records.some((r) => r.addedNodes.length > 0)) activate();
672
+ else dropRemovedBlocker();
543
673
  });
544
674
  const target = root instanceof Document ? root.documentElement : root;
545
675
  observer.observe(target, {
@@ -548,6 +678,7 @@ function unblockScripts(consent, options = {}) {
548
678
  });
549
679
  }
550
680
  return () => {
681
+ stopped = true;
551
682
  unsubscribe();
552
683
  observer?.disconnect();
553
684
  };
@@ -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/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,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,e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B,KAAK,EAAE,CAAC,GAAG;GACxF,IAAI,CAAC,QAAQ,EAAE,GAAG;GAClB,MAAM,SAAS,SAAS,cAAc,QAAQ;GAC9C,KAAK,MAAM,EAAE,MAAM,WAAW,MAAM,KAAK,GAAG,UAAU,GAAG;IACvD,IAAI,SAAS,UAAU,SAAS,aAAa;IAC7C,OAAO,aAAa,MAAM,KAAK;GACjC;GACA,MAAM,OAAO,GAAG,aAAa,WAAW;GACxC,IAAI,MAAM,OAAO,aAAa,QAAQ,IAAI;GAG1C,MAAM,EAAE,UAAU;GAClB,IAAI,OAAO,OAAO,QAAQ;GAC1B,IAAI,CAAC,GAAG,aAAa,KAAK,GAAG,OAAO,OAAO,GAAG,eAAe;GAC7D,GAAG,YAAY,MAAM;EACvB;EACA,KAAK,MAAM,MAAM,MAAM,KAAK,KAAK,iBAAiB,IAAI,KAAK,wBAAwB,CAAC,GAAG;GACrF,IAAI,CAAC,QAAQ,EAAE,GAAG;GAClB,MAAM,MAAM,GAAG,aAAa,UAAU;GACtC,GAAG,gBAAgB,UAAU;GAC7B,IAAI,KAAK,GAAG,aAAa,OAAO,GAAG;EACrC;CACF;CAEA,SAAS;CACT,MAAM,cAAc,QAAQ,UAAU,QAAQ;CAE9C,IAAI;CACJ,KAAK,QAAQ,WAAW,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 rejectSharedMachineNames(vendors)\n return { vendors, listed }\n}\n\n/**\n * Every vendor and cookie key must name one thing: `google` + cookie `analytics` comes out\n * `google_analytics`, the key of the Google Analytics vendor — both would render the same text.\n * (Within one vendor, and between vendor ids, this is already checked as they're declared.)\n */\nfunction rejectSharedMachineNames(vendors: readonly ConsentVendor[]): void {\n const owners = new Map<string, string>()\n const claim = (key: string, owner: string) => {\n const other = owners.get(key)\n if (other !== undefined && other !== owner) {\n const first = other.charAt(0).toUpperCase() + other.slice(1)\n throw new ConsentError(`${first} and ${owner} have the same machine name \"${key}\".`)\n }\n owners.set(key, owner)\n }\n for (const vendor of vendors) {\n claim(vendor.machine_name, `vendor \"${vendor.id}\"`)\n for (const cookie of vendor.cookies) {\n claim(cookie.machine_name, `vendor \"${vendor.id}\" cookie \"${cookie.name}\"`)\n }\n }\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 — so the banner closes and the visitor's choice applies, instead of being asked again on\n // every click — until the store changes after all (another tab stores a decision, or a later write\n // here lands). `undefined`: the store is the source of truth.\n let unsaved: StoredConsent | null | undefined\n // What the store held when `unsaved` was set. read() is referentially stable between changes, so\n // a different value means the store has changed since, and its decision is the newer one.\n let unsavedOver: StoredConsent | null = null\n const listeners = new Set<() => void>()\n const notify = () => {\n for (const fn of [...listeners]) fn()\n }\n const read = (): StoredConsent | null => {\n const stored = store.read()\n if (unsaved === undefined) return stored\n if (stored === unsavedOver) return unsaved\n unsaved = undefined\n return stored\n }\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 // Did it land? A store announces a write it kept (synchronously, to its subscribers); one that\n // fails quietly announces nothing and still reads back the very same value. Any change counts as\n // landed — including a listener that reset() or decided again while the write was announced:\n // that newer change must stand.\n const before = store.read()\n let announced = false\n const stopWatching = store.subscribe(() => {\n announced = true\n })\n try {\n store.write(record)\n } finally {\n stopWatching()\n }\n const kept = store.read()\n const landed = announced || kept !== before\n unsaved = landed ? undefined : record\n unsavedOver = kept\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 // A wrapper of its own per call: subscribing one function twice gives two subscriptions, and\n // ending one leaves the other.\n const listener = () => onChange()\n listeners.add(listener)\n const unsubscribe = store.subscribe(listener)\n return () => {\n listeners.delete(listener)\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/**\n * The paths a cookie may have been set for, from the root down to this page — each parent with and\n * without a trailing `/` (`Path=/a/` is sent on `/a/b` too): `/a/b` → `/`, `/a`, `/a/`, `/a/b`. The\n * page's own path gets its `/` variant only when the URL has one.\n * @internal\n */\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++) {\n const path = `/${segments.slice(0, i).join('/')}`\n paths.push(path)\n if (i < segments.length || pathname.endsWith('/')) paths.push(`${path}/`)\n }\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, protocol } = doc.location\n // In a secure context, expire with Secure: a browser refuses a `__Secure-` / `__Host-` cookie\n // without it (and Secure never stops a write from replacing a plain cookie there). On https that's\n // all it takes. http://localhost is a secure context too, but not every browser accepts a Secure\n // write there (older Safari): try both — a refused variant does nothing.\n const secureContext = doc.defaultView?.isSecureContext ?? protocol === 'https:'\n const variants = !secureContext ? [''] : protocol === 'https:' ? ['; Secure'] : ['', '; Secure']\n const expired = 'Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT'\n for (const secure of variants) {\n // A `__Host-` cookie exists only one way — host-only, Path=/, Secure — and is refused otherwise.\n if (name.startsWith('__Host-')) {\n doc.cookie = `${name}=; Path=/${secure}; ${expired}`\n continue\n }\n for (const domain of domainCandidates(hostname)) {\n for (const path of pathCandidates(pathname)) {\n doc.cookie = `${name}=; Path=${path}${domain ? `; Domain=${domain}` : ''}${secure}; ${expired}`\n }\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// External scripts inserted in order and not loaded yet, across every unblockScripts() call — so an\n// inline script of a new call (a React effect run again) still waits for what a stopped one put in.\nconst loading = new Set<HTMLScriptElement>()\n\n/** A script still loading in `doc` (one taken out of the page holds nothing up, and is forgotten). */\nfunction loadingIn(doc: Document | null): HTMLScriptElement | undefined {\n for (const script of loading) {\n if (!script.isConnected) loading.delete(script)\n else if (script.ownerDocument === doc) return script\n }\n return undefined\n}\n\n/** Call `fn` once when `script` has loaded or failed. */\nfunction onSettled(script: HTMLScriptElement, fn: () => void) {\n script.addEventListener('load', fn, { once: true })\n script.addEventListener('error', fn, { once: true })\n}\n\nconst JS_TYPE =\n /^(?:(?:application|text)\\/(?:x-)?(?:java|ecma)script|text\\/(?:jscript|livescript|javascript1\\.[0-5]))$/i\n\n/**\n * Whether an external script holds up the inline ones after it, and runs in order with the external\n * ones (`async = false`): the browser fires `load` or `error` for it.\n * An `async` one doesn't wait; one the browser won't run (a `nomodule` script, a type that isn't\n * JavaScript) fires neither event, and waiting on it would block everything after it for good.\n */\nfunction holdsUpOthers(el: Element, type: string | null): boolean {\n if (el.hasAttribute('async')) return false\n const t = (type ?? '').trim()\n if (t.toLowerCase() === 'module') return true\n if (t !== '' && !JS_TYPE.test(t)) return false\n return !el.hasAttribute('nomodule')\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. Scripts run in document order, as the parser would run them: consecutive\n * external ones download in parallel and run in order, and an inline one waits until every external script above it\n * has loaded (or failed). An `async` script holds nothing up. 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 // Scripts run in document order, like the parser would. External ones go in right away with\n // async = false — the browser then runs them in insertion order, while they download in parallel.\n // An inline one runs the moment it's inserted, so it waits until every external script above it\n // has loaded (or failed). An `async` script holds nothing up.\n const queue: Element[] = []\n const queued = new WeakSet<Element>()\n let waitingOn: HTMLScriptElement | null = null\n let stopped = false\n\n const insert = (el: Element) => {\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 else if (holdsUpOthers(el, type)) {\n script.async = false\n loading.add(script)\n onSettled(script, () => loading.delete(script))\n }\n el.replaceWith(script)\n }\n\n const waitFor = (script: HTMLScriptElement) => {\n waitingOn = script\n onSettled(script, () => {\n if (waitingOn !== script) return\n waitingOn = null\n drain()\n })\n }\n\n /** A script waited on but taken out of the page never settles: stop waiting, it holds nothing up. */\n const dropRemovedBlocker = () => {\n if (waitingOn?.isConnected !== false) return\n waitingOn = null\n drain()\n }\n\n const drain = () => {\n while (waitingOn === null && !stopped && queue.length > 0) {\n const el = queue[0] as Element\n // Consent may have changed while it waited (withdrawn: it stays blocked, and a later grant\n // picks it up again), or it was taken out of the page.\n if (!el.isConnected || !allowed(el)) {\n queue.shift()\n queued.delete(el)\n continue\n }\n if (!el.hasAttribute('src')) {\n const blocker = loadingIn(el.ownerDocument)\n if (blocker) return waitFor(blocker)\n }\n queue.shift()\n insert(el)\n }\n }\n\n const activate = () => {\n dropRemovedBlocker()\n for (const el of Array.from(root.querySelectorAll(`script[type=\"text/plain\"][${attr}]`))) {\n if (queued.has(el) || !allowed(el)) continue\n queued.add(el)\n queue.push(el)\n }\n drain()\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 else dropRemovedBlocker()\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 stopped = true\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,QAAQ;CAC1B;;CAGA,OAAO,OAAiC;EACtC,IACE,KAAK,eAAe,MAAM,cAC1B,KAAK,mBAAmB,MAAM,kBAC9B,KAAK,eAAe,MAAM,cAC1B,KAAKA,SAAS,SAAS,MAAMA,SAAS,MAEtC,OAAO;EAET,KAAK,MAAM,MAAM,KAAKA,UAAU,IAAI,CA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F,IAAI,OAAO,IAAI,EAAE,KAAK,CAAC,QAAQ,EAAE,GAAG;GACpC,OAAO,IAAI,EAAE;GACb,MAAM,KAAK,EAAE;EACf;EACA,MAAM;EACN,KAAK,MAAM,MAAM,MAAM,KAAK,KAAK,iBAAiB,IAAI,KAAK,wBAAwB,CAAC,GAAG;GACrF,IAAI,CAAC,QAAQ,EAAE,GAAG;GAClB,MAAM,MAAM,GAAG,aAAa,UAAU;GACtC,GAAG,gBAAgB,UAAU;GAC7B,IAAI,KAAK,GAAG,aAAa,OAAO,GAAG;EACrC;CACF;CAEA,SAAS;CACT,MAAM,cAAc,QAAQ,UAAU,QAAQ;CAE9C,IAAI;CACJ,KAAK,QAAQ,WAAW,SAAS,OAAO,qBAAqB,aAAa;EACxE,WAAW,IAAI,kBAAkB,YAAY;GAC3C,IAAI,QAAQ,MAAM,MAAM,EAAE,WAAW,SAAS,CAAC,GAAG,SAAS;QACtD,mBAAmB;EAC1B,CAAC;EACD,MAAM,SAAS,gBAAgB,WAAW,KAAK,kBAAmB;EAClE,SAAS,QAAQ,QAAQ;GAAE,WAAW;GAAM,SAAS;EAAK,CAAC;CAC7D;CAEA,aAAa;EACX,UAAU;EACV,YAAY;EACZ,UAAU,WAAW;CACvB;AACF"}
@@ -67,6 +67,7 @@ function toConsentVendor(declaration) {
67
67
  const where = `Vendor "${declaration.id}"`;
68
68
  const machine_name = toMachineName(declaration.id);
69
69
  if (machine_name === "") throw new ConsentError(`${where}: the id needs letters or digits for its machine name.`);
70
+ if (machine_name === "consent" || machine_name.startsWith("consent_")) throw new ConsentError(`${where}: the machine names "consent" and "consent_…" are reserved for the package's own keys.`);
70
71
  const byMachineName = /* @__PURE__ */ new Map();
71
72
  const cookies = declaration.cookies.map((cookie) => {
72
73
  const key = cookieMachineName(machine_name, cookie.name);
@@ -134,4 +135,4 @@ Object.defineProperty(exports, "toConsentVendor", {
134
135
  }
135
136
  });
136
137
 
137
- //# sourceMappingURL=machine-names-DCujHBVM.cjs.map
138
+ //# sourceMappingURL=machine-names--nw4DSRE.cjs.map