@luwiostack/cookie-consent 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,8 +4,8 @@ Cookie consent for React apps. The four categories are fixed: necessary, prefere
4
4
  and marketing. Per category, you list the vendors your site uses there; every cookie a vendor sets
5
5
  carries its category, so a vendor brings only its cookies of the categories you use it in. The
6
6
  decision is kept in `localStorage`, and the visitor is asked again when the policy changes or a
7
- year passes. The package also has a gate for embeds, Google Consent Mode v2, script unblocking,
8
- removal of a withdrawn category's cookies and ready-made vendor presets. There is no UI: every app
7
+ year passes. The package also has a gate for embeds, script unblocking, removal of a withdrawn
8
+ category's cookies and ready-made vendor presets. There is no UI: every app
9
9
  builds its own banner and preferences on `useConsent()`.
10
10
 
11
11
  ```bash
@@ -16,14 +16,69 @@ npm i @luwiostack/cookie-consent
16
16
 
17
17
  ```ts
18
18
  // consent.ts
19
- import { createConsent } from '@luwiostack/cookie-consent'
20
- import { googleAds, googleAnalytics, youtube } from '@luwiostack/cookie-consent/vendors'
19
+ import {
20
+ type ConsentTransferDeclaration,
21
+ type ConsentVendorDeclaration,
22
+ createConsent,
23
+ } from '@luwiostack/cookie-consent'
24
+
25
+ const DAY = 24 * 60 * 60 * 1000
26
+
27
+ // Every vendor in full: the same shape your backend sends (see "Config from your backend").
28
+ // A cookie without a domain is first-party; one with a domain is set on the vendor's.
29
+ const googleTransfers: ConsentTransferDeclaration[] = [
30
+ { country: 'GB', safeguards: ['adequacy'] },
31
+ { country: 'JP', safeguards: ['adequacy'] },
32
+ { country: 'US', safeguards: ['dpf', 'scc'] },
33
+ ]
34
+
35
+ const googleAnalytics: ConsentVendorDeclaration = {
36
+ id: 'google_analytics',
37
+ privacy_policy_url: 'https://policies.google.com/privacy',
38
+ transfers: googleTransfers,
39
+ cookies: [
40
+ { name: '_ga', category: 'statistics', max_age: 730 * DAY },
41
+ { name: '_ga_*', category: 'statistics', max_age: 730 * DAY },
42
+ ],
43
+ }
44
+
45
+ const youtube: ConsentVendorDeclaration = {
46
+ id: 'youtube',
47
+ privacy_policy_url: 'https://policies.google.com/privacy',
48
+ transfers: googleTransfers,
49
+ cookies: [
50
+ { name: 'PREF', category: 'preferences', max_age: 240 * DAY, domain: '.youtube.com' },
51
+ { name: 'YSC', category: 'marketing', max_age: 'session', domain: '.youtube.com' },
52
+ { name: 'VISITOR_INFO1_LIVE', category: 'marketing', max_age: 180 * DAY, domain: '.youtube.com' },
53
+ ],
54
+ }
55
+
56
+ const metaPixel: ConsentVendorDeclaration = {
57
+ id: 'meta_pixel',
58
+ privacy_policy_url: 'https://www.facebook.com/privacy/policy/',
59
+ transfers: [{ country: 'US', safeguards: ['dpf'] }],
60
+ cookies: [
61
+ { name: '_fbp', category: 'marketing', max_age: 90 * DAY },
62
+ { name: 'fr', category: 'marketing', max_age: 90 * DAY, domain: '.facebook.com' },
63
+ ],
64
+ }
65
+
66
+ // Your own strictly necessary cookies — always allowed, never asked.
67
+ const mySite: ConsentVendorDeclaration = {
68
+ id: 'my_site',
69
+ cookies: [
70
+ { name: 'session', category: 'necessary', max_age: 'session' },
71
+ { name: 'luwio.consent', category: 'necessary', type: 'local_storage', max_age: 'persistent' },
72
+ ],
73
+ }
21
74
 
22
75
  export const consent = createConsent({
76
+ // Per category, the vendors your site uses there. A vendor brings only its cookies of that category.
23
77
  categories: {
24
- statistics: [googleAnalytics()],
25
- preferences: [youtube()], // the YouTube embed — without YouTube's marketing cookies
26
- marketing: [googleAds({ cookies: ['_gcl_au', 'IDE'] })],
78
+ necessary: [mySite],
79
+ statistics: [googleAnalytics],
80
+ preferences: [youtube], // the YouTube embed (PREF) — without YouTube's marketing cookies
81
+ marketing: [metaPixel],
27
82
  },
28
83
  policyVersion: 1, // bump when the vendors change → everyone is asked again
29
84
  // maxAge: 365 days by default
@@ -38,10 +93,18 @@ consent.isGranted('marketing', 'youtube') // false — not used there, so no t
38
93
  ```
39
94
 
40
95
  A vendor listed under a category brings only its cookies of that category, plus its necessary
41
- cookies, which are always allowed. So `preferences: [youtube()]` is the embed alone (`PREF`). Add
42
- `youtube()` to `marketing` as well to declare YouTube's tracking cookies, and the vendor then needs
96
+ cookies, which are always allowed. So `preferences: [youtube]` is the embed alone (`PREF`). Add
97
+ `youtube` to `marketing` as well to declare YouTube's tracking cookies, and the vendor then needs
43
98
  both categories. Listing a vendor under a category it has no cookies in throws.
44
99
 
100
+ Each listing may also declare the vendor differently, for example a preset narrowed per category
101
+ (`youtube({ cookies: ['PREF'] })` under preferences, `youtube({ cookies: ['YSC'] })` under
102
+ marketing). The vendor then gets the cookies of every listing. Its `privacy_policy_url` and
103
+ `transfers`, and a cookie listed twice, must be declared the same way each time, or it throws.
104
+
105
+ In production the declarations come from your backend, in this same shape: see
106
+ [Config from your backend](#config-from-your-backend).
107
+
45
108
  **Where the decision is kept.** By default in `localStorage` (`luwio.consent`), synced across
46
109
  tabs. A stored decision stops counting when its policy version differs, when it's older than
47
110
  `maxAge`, or when it's dated in the future (it could never expire; a few minutes of clock drift are
@@ -51,8 +114,9 @@ the page's life** — the banner closes, gates open — and they're asked again
51
114
 
52
115
  `consent.categories` is always the four categories, in order (`CONSENT_CATEGORIES`). Each one
53
116
  carries the vendors used in it, and only those cookies. `necessary` is required: it is
54
- always granted and never part of the question. Categories carry no text, so render
55
- `` t(`category.${id}`) `` from the catalogs below.
117
+ always granted and never part of the question. Categories carry no text: like every LuwioStack
118
+ domain object they have a `machine_name`, so render `t(category.machine_name)` (and
119
+ `t(category.description_machine_name)`) from the catalogs below.
56
120
 
57
121
  ## React
58
122
 
@@ -102,6 +166,30 @@ product. `useConsent()` gives you what they need:
102
166
  Keep your preferences' unsaved ticks in your own state, starting from `isGranted`, so nothing is
103
167
  ever pre-ticked. `apps/showcase` (`src/app/CookieBanner.tsx`) is a full example.
104
168
 
169
+ ### Pages without the banner
170
+
171
+ Don't let the banner cover the page that explains it: the privacy and cookie policy, the legal
172
+ notice. Where the banner shows is your app's call, so decide it per route. With
173
+ `@luwiostack/router`, flag the route with `staticData` and read the flag in your banner:
174
+
175
+ ```tsx
176
+ // privacy.route.tsx
177
+ createRoute({ id: 'privacy', staticData: { hideCookieBanner: true }, … })
178
+
179
+ // CookieBanner.tsx
180
+ const { needsDecision, isPreferencesOpen } = useConsent()
181
+ const hideBanner = useRouteStaticData((d) => d.hideCookieBanner === true)
182
+ if (isPreferencesOpen) return <Preferences />
183
+ if (needsDecision && !hideBanner) return <Banner />
184
+ return null
185
+ ```
186
+
187
+ Type the flag once by augmenting `RouteStaticData` (see the router README). Hide only the
188
+ **banner**, not the preferences: a visitor who opens "Cookie settings" on the privacy page gets them.
189
+ Nothing is unblocked meanwhile: the status stays `pending`, so only `necessary` is granted, and the
190
+ banner shows again on the next page. Prefer a route flag over checking the pathname, which breaks
191
+ as soon as the slug is translated.
192
+
105
193
  ## Vendors and their cookies
106
194
 
107
195
  Most cookies come from the same handful of services, so the package ships their declarations at
@@ -119,7 +207,7 @@ metaPixel({ extra: [{ name: 'my_flag', category: 'marketing', max_age: 'session'
119
207
  // Your own site's necessary cookies: never asked about, but they must be declared. List them under
120
208
  // `necessary` — the session, CSRF token and this choice's own storage item.
121
209
  const mySite = {
122
- id: 'my_site', // t('my_site'), t('my_site.session') … in your own catalog
210
+ id: 'my_site', // t('my_site'), t('my_site_session') … in your own catalog
123
211
  cookies: [
124
212
  { name: 'session', category: 'necessary', max_age: 'session' },
125
213
  { name: 'luwio.consent', category: 'necessary', type: 'local_storage', max_age: 'persistent' },
@@ -133,28 +221,63 @@ const DAY = 24 * 60 * 60 * 1000
133
221
  export const acmeChat = defineVendor({
134
222
  id: 'acme_chat', // t('acme_chat') → the name
135
223
  privacy_policy_url: 'https://acme.example/privacy',
224
+ transfers: [{ country: 'US', safeguards: ['dpf', 'scc'] }], // [] when the data stays in the EEA
136
225
  cookies: [
137
226
  { name: 'acme_id', category: 'preferences', max_age: 365 * DAY }, // type defaults to 'http'
138
227
  { name: 'acme_open', category: 'necessary', type: 'session_storage', max_age: 'session' },
228
+ { name: 'acme_ad', category: 'marketing', max_age: 90 * DAY, domain: '.acme.example' },
139
229
  ],
140
230
  })
141
231
  ```
142
232
 
143
- Each cookie has a `category`, a `max_age` and an optional `type`:
233
+ Each cookie has a `category`, a `max_age` and an optional `type` and `domain`:
144
234
 
145
235
  - `max_age` is milliseconds, `'session'` or `'persistent'`.
146
236
  - `type` is `http` (the default), `local_storage`, `session_storage`, `indexed_db` or `pixel`.
237
+ - `domain` is the vendor's domain a third-party cookie is set on (`.youtube.com`); leave it out for
238
+ one on your own domain. The resolved cookie carries `party`: `first` or `third`.
239
+
240
+ A vendor's `transfers` lists the countries outside the EEA it sends personal data to, each with its
241
+ safeguards: `adequacy` (an EU adequacy decision), `dpf` (EU-US Data Privacy Framework), `scc`
242
+ (standard contractual clauses) or `bcr` (binding corporate rules). `[]` says the data stays in the
243
+ EEA; leaving it out says nothing. Every preset declares it.
147
244
 
148
245
  `ConsentCookieFormatter.formatLocale(cookie, locale)` renders a lifetime as "2 years" or "3
149
- months". It returns `null` for `session` and `persistent`; translate those yourself.
246
+ months". It returns `null` for `session` and `persistent`: translate those with
247
+ `t(cookie.max_age_machine_name)`.
248
+
249
+ Every text has one translation key, a snake_case `machine_name` the consent instance hands out —
250
+ nothing builds a key itself. The text lives in the downloadable catalogs
251
+ (`translations/cookie-consent.<locale>.json`, in en, nl, fr, de and es):
252
+
253
+ | Render | Key | Example |
254
+ | --- | --- | --- |
255
+ | `t(category.machine_name)` | `consent_category_<id>` | `consent_category_statistics` |
256
+ | `t(category.description_machine_name)` | `consent_category_<id>_description` | `consent_category_statistics_description` |
257
+ | `t(vendor.machine_name)` | the vendor id as a machine name | `google_analytics` |
258
+ | `t(cookie.machine_name)` (its purpose) | the vendor's plus the cookie name, `*` as `wildcard` | `google_analytics_ga`, `google_analytics_ga_wildcard` (`_ga_*`) |
259
+ | `t(cookie.type_machine_name)` | `consent_cookie_type_<type>` | `consent_cookie_type_local_storage` |
260
+ | `t(cookie.max_age_machine_name)` | `consent_max_age_<word>` | `consent_max_age_session` |
261
+ | `t(cookie.party_machine_name)` | `consent_cookie_party_<party>` | `consent_cookie_party_third` |
262
+ | `t(key)` for each of `transfer.safeguard_machine_names` | `consent_transfer_safeguard_<safeguard>` | `consent_transfer_safeguard_dpf` |
263
+
264
+ A transfer's `country` is an ISO code: name it with `new Intl.DisplayNames([locale], { type: 'region' })`.
150
265
 
151
- The text lives in the downloadable catalogs (`translations/cookie-consent.<locale>.json`, in en, nl, fr,
152
- de and es):
266
+ ```tsx
267
+ <h3>{t(vendor.machine_name)}</h3>
268
+ {vendor.cookies.map((cookie) => (
269
+ <tr key={cookie.name}>
270
+ <td><code>{cookie.name}</code></td>
271
+ <td>{t(cookie.machine_name)}</td>
272
+ <td>{ConsentCookieFormatter.formatLocale(cookie, locale) ?? t(cookie.max_age_machine_name ?? '')}</td>
273
+ <td>{t(cookie.type_machine_name)}</td>
274
+ </tr>
275
+ ))}
276
+ ```
153
277
 
154
- - `category.<id>` and `category.<id>.description` name and describe the four categories.
155
- - `t(vendor.id)` is a vendor's name.
156
- - `` t(`${vendor.id}.${cookie.name}`) `` is a cookie's purpose.
157
- - `cookie_type.<type>`, `max_age.session` and `max_age.persistent` cover the rest.
278
+ You declare vendors (`ConsentVendorDeclaration`: `id` and `cookies`, each a
279
+ `ConsentCookieDeclaration`); the machine names are derived. Two cookie names — or two vendor ids —
280
+ that come out as the same machine name throw a `ConsentError`, as does one without letters or digits.
158
281
 
159
282
  ### Config from your backend
160
283
 
@@ -213,9 +336,8 @@ vendor still brings its own necessary cookies (reCAPTCHA's, say) under the categ
213
336
  ## Outside React
214
337
 
215
338
  ```ts
216
- import { clearRevokedCookies, googleConsentMode, unblockScripts } from '@luwiostack/cookie-consent'
339
+ import { clearRevokedCookies, unblockScripts } from '@luwiostack/cookie-consent'
217
340
 
218
- googleConsentMode(consent) // before gtag.js / GTM loads; standard mapping (ads → marketing, …)
219
341
  unblockScripts(consent) // activates <script type="text/plain" data-consent="statistics">,
220
342
  // plus data-consent-vendor="meta_pixel" to also need that vendor there
221
343
  clearRevokedCookies(consent) // removes the cookies / storage of categories that aren't granted
@@ -256,8 +378,7 @@ clearRevokedCookies(consent, {
256
378
  ## Compliance checklist
257
379
 
258
380
  The four categories are granular enough for GDPR / ePrivacy; what regulators check is how the
259
- choice is collected. The package covers prior blocking (`ConsentGate`, `unblockScripts`, Consent
260
- Mode's denied default), removal on withdrawal (`clearRevokedCookies`), the cookie declaration,
381
+ choice is collected. The package covers prior blocking (`ConsentGate`, `unblockScripts`), removal on withdrawal (`clearRevokedCookies`), the cookie declaration,
261
382
  re-asking (`policyVersion`, `maxAge`) and the data for a consent log (`onChange`). Your app covers
262
383
  the rest:
263
384
 
@@ -271,7 +392,8 @@ the rest:
271
392
  Watch out for: Google-served ads (AdSense, Ad Manager, AdMob) in the EEA / UK need a
272
393
  Google-certified TCF CMP, which this isn't; the CNIL recommends re-asking after about 6 months
273
394
  (set `maxAge`); California expects a Global Privacy Control signal to count as refusing marketing
274
- (not read by the package); name US vendors in your privacy policy. Guidance, not legal advice.
395
+ (not read by the package); name the countries and safeguards of each vendor's `transfers` in your
396
+ cookie declaration and privacy policy. Guidance, not legal advice.
275
397
 
276
398
  ## API
277
399
 
@@ -279,12 +401,13 @@ Google-certified TCF CMP, which this isn't; the CNIL recommends re-asking after
279
401
  | --- | --- |
280
402
  | `createConsent({ categories?, policyVersion?, maxAge?, store?, now?, onChange? })` | The consent instance; `categories` maps each fixed category to the vendors used in it. |
281
403
  | `CONSENT_CATEGORIES` · `ConsentCategoryId` | `necessary`, `preferences`, `statistics`, `marketing`. |
282
- | `consent.categories` · `consent.vendors` | The four categories with their vendors (cookies narrowed per category); every vendor in use once. |
404
+ | `consent.categories` · `consent.vendors` | The four categories with their vendors (cookies narrowed per category); every vendor in use once. Each with its `machine_name`s. |
405
+ | `ConsentVendorDeclaration` · `ConsentCookieDeclaration` · `ConsentTransferDeclaration` | What you declare: `{ id, privacy_policy_url?, transfers?, cookies }`, `{ name, category, type?, max_age, domain? }`, `{ country, safeguards }`. |
406
+ | `ConsentCategory` · `ConsentVendor` · `ConsentCookie` · `ConsentTransfer` | What you render: the same plus `machine_name` (and `description_machine_name`, `type_machine_name`, `party`, `party_machine_name`, `max_age_machine_name?`, `safeguard_machine_names`). |
283
407
  | `consent.getSnapshot()` | `{ status: 'pending' \| 'decided', decision }`. |
284
408
  | `consent.isGranted(category, vendorId?)` / `isRequired(category)` | `necessary` is always granted. With a vendor, also whether it's used in that category. |
285
409
  | `consent.acceptAll()` / `rejectAll()` / `save(ids)` / `grant(...ids)` / `revoke(...ids)` / `reset()` | Make (or forget) a decision. |
286
410
  | `ConsentDecision` | `consent_id`, `policy_version`, `decided_at`, `granted()`, `isGranted(id)`, `toJSON()`. |
287
- | `googleConsentMode(consent, { mapping?, region?, waitForUpdate?, adsDataRedaction?, urlPassthrough?, gtag? })` | Google Consent Mode v2 default + updates; `DEFAULT_GOOGLE_CONSENT_MAPPING` unless you pass one. |
288
411
  | `unblockScripts(consent, options?)` | Activate blocked scripts / `data-src` embeds. |
289
412
  | `clearRevokedCookies(consent, { onClear? })` | Remove declared first-party cookies and storage of every category that isn't granted. |
290
413
  | `ConsentCookieFormatter.formatLocale(cookie, locale)` | A lifetime as "2 years" / "3 months"; `null` for session / persistent. |
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_errors = require("./errors-BqpghFQf.cjs");
2
+ const require_machine_names = require("./machine-names-DCujHBVM.cjs");
3
3
  const require_used_vendors = require("./used-vendors-C8uSNIkd.cjs");
4
4
  let _luwiostack_storage = require("@luwiostack/storage");
5
5
  //#region src/domain/consent-decision.ts
@@ -24,9 +24,9 @@ var ConsentDecision = class ConsentDecision {
24
24
  }
25
25
  /** @throws {ConsentError} on an empty `consent_id` / `policy_version` or a non-finite `decided_at`. */
26
26
  static new(input) {
27
- if (typeof input.consent_id !== "string" || input.consent_id === "") throw new require_errors.ConsentError("A consent decision needs a non-empty consent_id.");
28
- if (typeof input.policy_version !== "string" || input.policy_version === "") throw new require_errors.ConsentError("A consent decision needs a non-empty policy_version.");
29
- if (typeof input.decided_at !== "number" || !Number.isFinite(input.decided_at)) throw new require_errors.ConsentError("A consent decision needs decided_at as finite epoch milliseconds.");
27
+ if (typeof input.consent_id !== "string" || input.consent_id === "") throw new require_machine_names.ConsentError("A consent decision needs a non-empty consent_id.");
28
+ if (typeof input.policy_version !== "string" || input.policy_version === "") throw new require_machine_names.ConsentError("A consent decision needs a non-empty policy_version.");
29
+ if (typeof input.decided_at !== "number" || !Number.isFinite(input.decided_at)) throw new require_machine_names.ConsentError("A consent decision needs decided_at as finite epoch milliseconds.");
30
30
  return new ConsentDecision(input);
31
31
  }
32
32
  /** Like {@link ConsentDecision.new}, but returns `null` instead of throwing. */
@@ -80,18 +80,43 @@ const COOKIE_TYPES = /* @__PURE__ */ new Set([
80
80
  ]);
81
81
  /** Checks one vendor declaration: an id, unique cookie names, valid categories and lifetimes. */
82
82
  function validateVendor(vendor, listedIn) {
83
- if (typeof vendor?.id !== "string" || vendor.id === "") throw new require_errors.ConsentError(`Category "${listedIn}": a vendor id must be non-empty.`);
83
+ if (typeof vendor?.id !== "string" || vendor.id === "") throw new require_machine_names.ConsentError(`Category "${listedIn}": a vendor id must be non-empty.`);
84
84
  const where = `Vendor "${vendor.id}"`;
85
- if (!Array.isArray(vendor.cookies)) throw new require_errors.ConsentError(`${where}: cookies must be an array.`);
85
+ if (!Array.isArray(vendor.cookies)) throw new require_machine_names.ConsentError(`${where}: cookies must be an array.`);
86
+ validateTransfers(vendor.transfers, where);
86
87
  const names = /* @__PURE__ */ new Set();
87
88
  for (const cookie of vendor.cookies) {
88
- if (typeof cookie.name !== "string" || cookie.name === "") throw new require_errors.ConsentError(`${where}: a cookie name must be non-empty.`);
89
- if (names.has(cookie.name)) throw new require_errors.ConsentError(`${where}: duplicate cookie "${cookie.name}".`);
89
+ if (typeof cookie !== "object" || cookie === null) throw new require_machine_names.ConsentError(`${where}: every cookie must be an object.`);
90
+ if (typeof cookie.name !== "string" || cookie.name === "") throw new require_machine_names.ConsentError(`${where}: a cookie name must be non-empty.`);
91
+ if (names.has(cookie.name)) throw new require_machine_names.ConsentError(`${where}: duplicate cookie "${cookie.name}".`);
90
92
  names.add(cookie.name);
91
- if (!require_errors.isConsentCategoryId(cookie.category)) throw new require_errors.ConsentError(`${where}: cookie "${cookie.name}" needs a category (${require_errors.CONSENT_CATEGORIES.join(", ")}).`);
92
- if (cookie.type !== void 0 && !COOKIE_TYPES.has(cookie.type)) throw new require_errors.ConsentError(`${where}: cookie "${cookie.name}" has an unknown type "${cookie.type}".`);
93
+ if (!require_machine_names.isConsentCategoryId(cookie.category)) throw new require_machine_names.ConsentError(`${where}: cookie "${cookie.name}" needs a category (${require_machine_names.CONSENT_CATEGORIES.join(", ")}).`);
94
+ if (cookie.type !== void 0 && !COOKIE_TYPES.has(cookie.type)) throw new require_machine_names.ConsentError(`${where}: cookie "${cookie.name}" has an unknown type "${cookie.type}".`);
93
95
  const { max_age } = cookie;
94
- if (!(max_age === "session" || max_age === "persistent" || typeof max_age === "number" && Number.isFinite(max_age) && max_age > 0)) throw new require_errors.ConsentError(`${where}: cookie "${cookie.name}" needs max_age as positive milliseconds, 'session' or 'persistent'.`);
96
+ if (!(max_age === "session" || max_age === "persistent" || typeof max_age === "number" && Number.isFinite(max_age) && max_age > 0)) throw new require_machine_names.ConsentError(`${where}: cookie "${cookie.name}" needs max_age as positive milliseconds, 'session' or 'persistent'.`);
97
+ if (cookie.domain !== void 0 && (typeof cookie.domain !== "string" || !DOMAIN.test(cookie.domain))) throw new require_machine_names.ConsentError(`${where}: cookie "${cookie.name}" needs domain as a host name like ".youtube.com", or none for the site's own domain.`);
98
+ }
99
+ }
100
+ /** A cookie domain: a host name, optionally with a leading dot, no scheme, port or path. */
101
+ const DOMAIN = /^\.?[a-z0-9-]+(\.[a-z0-9-]+)+$/i;
102
+ const SAFEGUARDS = /* @__PURE__ */ new Set([
103
+ "adequacy",
104
+ "dpf",
105
+ "scc",
106
+ "bcr"
107
+ ]);
108
+ /** Transfers: absent, or per unique ISO alpha-2 country at least one known safeguard. */
109
+ function validateTransfers(transfers, where) {
110
+ if (transfers === void 0) return;
111
+ if (!Array.isArray(transfers)) throw new require_machine_names.ConsentError(`${where}: transfers must be an array.`);
112
+ const countries = /* @__PURE__ */ new Set();
113
+ for (const transfer of transfers) {
114
+ const country = transfer?.country;
115
+ if (typeof country !== "string" || !/^[A-Z]{2}$/.test(country)) throw new require_machine_names.ConsentError(`${where}: a transfer needs country as ISO alpha-2, e.g. "US".`);
116
+ if (countries.has(country)) throw new require_machine_names.ConsentError(`${where}: duplicate transfer "${country}".`);
117
+ countries.add(country);
118
+ const { safeguards } = transfer;
119
+ if (!Array.isArray(safeguards) || safeguards.length === 0 || !safeguards.every((s) => SAFEGUARDS.has(s))) throw new require_machine_names.ConsentError(`${where}: transfer "${country}" needs safeguards from ${[...SAFEGUARDS].join(", ")}.`);
95
120
  }
96
121
  }
97
122
  /**
@@ -100,38 +125,67 @@ function validateVendor(vendor, listedIn) {
100
125
  * of any use of the service). A vendor listed under several categories is merged into one.
101
126
  */
102
127
  function resolveVendors(config) {
103
- if (typeof config !== "object" || config === null || Array.isArray(config)) throw new require_errors.ConsentError("categories must be an object of category id → vendors.");
104
- for (const key of Object.keys(config)) if (!require_errors.isConsentCategoryId(key)) throw new require_errors.ConsentError(`Unknown consent category "${key}" — use ${require_errors.CONSENT_CATEGORIES.join(", ")}.`);
128
+ if (typeof config !== "object" || config === null || Array.isArray(config)) throw new require_machine_names.ConsentError("categories must be an object of category id → vendors.");
129
+ for (const key of Object.keys(config)) if (!require_machine_names.isConsentCategoryId(key)) throw new require_machine_names.ConsentError(`Unknown consent category "${key}" — use ${require_machine_names.CONSENT_CATEGORIES.join(", ")}.`);
105
130
  const merged = /* @__PURE__ */ new Map();
106
- const listed = Object.fromEntries(require_errors.CONSENT_CATEGORIES.map((id) => [id, []]));
107
- for (const category of require_errors.CONSENT_CATEGORIES) {
131
+ const idByMachineName = /* @__PURE__ */ new Map();
132
+ const listed = Object.fromEntries(require_machine_names.CONSENT_CATEGORIES.map((id) => [id, []]));
133
+ for (const category of require_machine_names.CONSENT_CATEGORIES) {
108
134
  const inCategory = config[category];
109
135
  if (inCategory === void 0) continue;
110
- if (!Array.isArray(inCategory)) throw new require_errors.ConsentError(`Category "${category}": vendors must be an array.`);
136
+ if (!Array.isArray(inCategory)) throw new require_machine_names.ConsentError(`Category "${category}": vendors must be an array.`);
111
137
  const seen = /* @__PURE__ */ new Set();
112
- for (const vendor of inCategory) {
113
- validateVendor(vendor, category);
138
+ for (const declaration of inCategory) {
139
+ validateVendor(declaration, category);
140
+ const vendor = require_machine_names.toConsentVendor(declaration);
141
+ const other = idByMachineName.get(vendor.machine_name);
142
+ if (other !== void 0 && other !== vendor.id) throw new require_machine_names.ConsentError(`Vendors "${other}" and "${vendor.id}" have the same machine name "${vendor.machine_name}".`);
143
+ idByMachineName.set(vendor.machine_name, vendor.id);
114
144
  const where = `Category "${category}", vendor "${vendor.id}"`;
115
- if (seen.has(vendor.id)) throw new require_errors.ConsentError(`${where}: duplicate vendor.`);
145
+ if (seen.has(vendor.id)) throw new require_machine_names.ConsentError(`${where}: duplicate vendor.`);
116
146
  seen.add(vendor.id);
117
147
  listed[category].push(vendor.id);
118
- if (vendor.cookies.filter((c) => c.category === category).length === 0) throw new require_errors.ConsentError(`${where}: the vendor has no ${category} cookies.`);
148
+ if (vendor.cookies.filter((c) => c.category === category).length === 0) throw new require_machine_names.ConsentError(`${where}: the vendor has no ${category} cookies.`);
119
149
  const entry = merged.get(vendor.id) ?? {
120
150
  vendor,
121
151
  cookies: /* @__PURE__ */ new Map()
122
152
  };
123
- for (const cookie of vendor.cookies) if (cookie.category === category || cookie.category === "necessary") entry.cookies.set(cookie.name, cookie);
153
+ if (entry.vendor !== vendor && !sameVendorInfo(entry.vendor, vendor)) throw new require_machine_names.ConsentError(`Vendor "${vendor.id}" is declared differently in two categories (privacy_policy_url or transfers).`);
154
+ for (const cookie of vendor.cookies) {
155
+ if (cookie.category !== category && cookie.category !== "necessary") continue;
156
+ const known = entry.cookies.get(cookie.name);
157
+ if (known !== void 0 && !sameCookie(known, cookie)) throw new require_machine_names.ConsentError(`Vendor "${vendor.id}": cookie "${cookie.name}" is declared differently in two categories.`);
158
+ const clash = [...entry.cookies.values()].find((c) => c.name !== cookie.name && c.machine_name === cookie.machine_name);
159
+ if (clash) throw new require_machine_names.ConsentError(`Vendor "${vendor.id}": cookies "${clash.name}" and "${cookie.name}" have the same machine name "${cookie.machine_name}".`);
160
+ entry.cookies.set(cookie.name, cookie);
161
+ }
124
162
  merged.set(vendor.id, entry);
125
163
  }
126
164
  }
127
165
  return {
128
- vendors: [...merged.values()].map(({ vendor, cookies }) => ({
129
- ...vendor,
130
- cookies: vendor.cookies.filter((c) => cookies.has(c.name))
131
- })),
166
+ vendors: [...merged.values()].map(({ vendor, cookies }) => {
167
+ const order = vendor.cookies.map((c) => c.name).filter((name) => cookies.has(name));
168
+ const ordered = new Set(order);
169
+ for (const name of cookies.keys()) if (!ordered.has(name)) order.push(name);
170
+ return {
171
+ ...vendor,
172
+ cookies: order.flatMap((name) => cookies.get(name) ?? [])
173
+ };
174
+ }),
132
175
  listed
133
176
  };
134
177
  }
178
+ function sameVendorInfo(a, b) {
179
+ return a.privacy_policy_url === b.privacy_policy_url && transfersKey(a.transfers) === transfersKey(b.transfers);
180
+ }
181
+ /** Transfers in a canonical form: the same countries and safeguards in any order compare equal. */
182
+ function transfersKey(transfers) {
183
+ if (transfers === void 0) return "none";
184
+ return transfers.map((t) => `${t.country}:${[...t.safeguards].sort().join(",")}`).sort().join(";");
185
+ }
186
+ function sameCookie(a, b) {
187
+ return a.category === b.category && (a.type ?? "http") === (b.type ?? "http") && a.max_age === b.max_age && a.domain === b.domain;
188
+ }
135
189
  function reusableId(record) {
136
190
  const id = record?.consent_id;
137
191
  return typeof id === "string" && id !== "" ? id : null;
@@ -169,11 +223,13 @@ function randomId() {
169
223
  function createConsent(config = {}) {
170
224
  const { vendors, listed } = resolveVendors(config.categories ?? {});
171
225
  const byId = new Map(vendors.map((v) => [v.id, v]));
172
- const categories = require_errors.CONSENT_CATEGORIES.map((id) => {
226
+ const categories = require_machine_names.CONSENT_CATEGORIES.map((id) => {
173
227
  const ids = [.../* @__PURE__ */ new Set([...listed[id], ...vendors.map((v) => v.id)])];
174
228
  return {
175
229
  id,
176
- required: id === require_errors.REQUIRED_CATEGORY,
230
+ machine_name: require_machine_names.categoryMachineName(id),
231
+ description_machine_name: `${require_machine_names.categoryMachineName(id)}_description`,
232
+ required: id === require_machine_names.REQUIRED_CATEGORY,
177
233
  vendors: ids.flatMap((vendorId) => {
178
234
  const vendor = byId.get(vendorId);
179
235
  const cookies = vendor.cookies.filter((c) => c.category === id);
@@ -186,8 +242,10 @@ function createConsent(config = {}) {
186
242
  });
187
243
  const usedIn = require_used_vendors.usedVendors(categories);
188
244
  const maxAge = config.maxAge ?? 31536e6;
189
- if (typeof maxAge !== "number" || Number.isNaN(maxAge) || maxAge <= 0) throw new require_errors.ConsentError("maxAge must be a positive number of milliseconds.");
190
- const policyVersion = String(config.policyVersion ?? 1);
245
+ if (typeof maxAge !== "number" || Number.isNaN(maxAge) || maxAge <= 0) throw new require_machine_names.ConsentError("maxAge must be a positive number of milliseconds.");
246
+ const rawVersion = config.policyVersion ?? 1;
247
+ if (!(typeof rawVersion === "string" && rawVersion !== "" || typeof rawVersion === "number" && Number.isFinite(rawVersion))) throw new require_machine_names.ConsentError("policyVersion must be a non-empty string or a finite number.");
248
+ const policyVersion = String(rawVersion);
191
249
  const store = config.store ?? (0, _luwiostack_storage.localStore)("luwio.consent", { onError: "ignore" });
192
250
  const now = config.now ?? Date.now;
193
251
  let unsaved;
@@ -202,8 +260,8 @@ function createConsent(config = {}) {
202
260
  function toDecision(record) {
203
261
  if (record.policy_version !== policyVersion) return null;
204
262
  if (!Array.isArray(record.granted)) return null;
205
- const granted = /* @__PURE__ */ new Set([require_errors.REQUIRED_CATEGORY]);
206
- for (const id of record.granted) if (require_errors.isConsentCategoryId(id)) granted.add(id);
263
+ const granted = /* @__PURE__ */ new Set([require_machine_names.REQUIRED_CATEGORY]);
264
+ for (const id of record.granted) if (require_machine_names.isConsentCategoryId(id)) granted.add(id);
207
265
  return ConsentDecision.tryNew({
208
266
  ...record,
209
267
  granted
@@ -228,12 +286,12 @@ function createConsent(config = {}) {
228
286
  }
229
287
  function commit(granted) {
230
288
  const previous = current();
231
- const set = /* @__PURE__ */ new Set([require_errors.REQUIRED_CATEGORY]);
232
- for (const id of granted) if (require_errors.isConsentCategoryId(id)) set.add(id);
289
+ const set = /* @__PURE__ */ new Set([require_machine_names.REQUIRED_CATEGORY]);
290
+ for (const id of granted) if (require_machine_names.isConsentCategoryId(id)) set.add(id);
233
291
  const next = ConsentDecision.new({
234
292
  consent_id: previous?.consent_id ?? reusableId(read()) ?? randomId(),
235
293
  policy_version: policyVersion,
236
- granted: require_errors.CONSENT_CATEGORIES.filter((id) => set.has(id)),
294
+ granted: require_machine_names.CONSENT_CATEGORIES.filter((id) => set.has(id)),
237
295
  decided_at: now()
238
296
  });
239
297
  const record = next.toJSON();
@@ -245,8 +303,8 @@ function createConsent(config = {}) {
245
303
  config.onChange?.(next, previous);
246
304
  return next;
247
305
  }
248
- const isRequired = (id) => id === require_errors.REQUIRED_CATEGORY;
249
- const isGranted = (id, vendorId) => (vendorId === void 0 || usedIn[id].has(vendorId)) && (isRequired(id) || (current()?.isGranted(id) ?? false));
306
+ const isRequired = (id) => id === require_machine_names.REQUIRED_CATEGORY;
307
+ const isGranted = (id, vendorId) => (vendorId === void 0 || usedIn[id]?.has(vendorId) === true) && (isRequired(id) || (current()?.isGranted(id) ?? false));
250
308
  return {
251
309
  categories,
252
310
  vendors,
@@ -262,7 +320,7 @@ function createConsent(config = {}) {
262
320
  },
263
321
  isGranted,
264
322
  isRequired,
265
- acceptAll: () => commit(require_errors.CONSENT_CATEGORIES),
323
+ acceptAll: () => commit(require_machine_names.CONSENT_CATEGORIES),
266
324
  rejectAll: () => commit([]),
267
325
  save: (granted) => commit(granted),
268
326
  grant: (...grant) => commit([...current()?.granted() ?? [], ...grant]),
@@ -300,8 +358,8 @@ var ConsentCookieFormatter = class {
300
358
  /**
301
359
  * A cookie's lifetime in `locale`, in the largest unit that divides it evenly: 2 years, 3 months,
302
360
  * 400 days, 30 minutes — falling back to whole days (or the largest unit that fits) when nothing
303
- * divides evenly. Returns `null` for `'session'` and `'persistent'`: those are words, so render
304
- * them through your own translations.
361
+ * divides evenly. Returns `null` for `'session'` and `'persistent'`: those are words, so translate
362
+ * them — `formatLocale(cookie, locale) ?? t(cookie.max_age_machine_name)`.
305
363
  */
306
364
  static formatLocale(cookie, locale, options = {}) {
307
365
  const { max_age } = cookie;
@@ -368,8 +426,9 @@ function storageKeys(storage) {
368
426
  *
369
427
  * Only **first-party** storage can be reached: cookies on your own domain (tried with every parent
370
428
  * domain and path, since tags set them broadly), `localStorage` / `sessionStorage` items and
371
- * IndexedDB databases. A third-party cookie (`IDE` on doubleclick.net) lives on another site and
372
- * can't be removed from yours; `HttpOnly` cookies only by your server. Scripts already running keep
429
+ * IndexedDB databases. A third-party cookie (declared with a `domain`, like `IDE` on
430
+ * doubleclick.net) lives on another site: it's skipped, so a first-party item that shares its name
431
+ * is never removed. `HttpOnly` cookies can only be removed by your server. Scripts already running keep
373
432
  * running — reload the page (e.g. from `onClear`) to stop them.
374
433
  *
375
434
  * Returns a stop function. A no-op on the server.
@@ -382,7 +441,7 @@ function clearRevokedCookies(consent, options = {}) {
382
441
  for (const category of consent.categories) {
383
442
  const granted = category.id === "necessary" || consent.isGranted(category.id);
384
443
  for (const vendor of category.vendors) for (const cookie of vendor.cookies) if (granted) kept.push(matcher(cookie.name));
385
- else revoked.push(cookie);
444
+ else if (cookie.domain === void 0) revoked.push(cookie);
386
445
  }
387
446
  if (revoked.length === 0) return;
388
447
  const isKept = (actual) => kept.some((matches) => matches(actual));
@@ -414,7 +473,7 @@ function clearRevokedCookies(consent, options = {}) {
414
473
  indexedDB.deleteDatabase(name);
415
474
  cleared(cookie, name);
416
475
  }
417
- });
476
+ }).catch(() => {});
418
477
  else if (!cookie.name.includes("*") && !isKept(cookie.name)) indexedDB.deleteDatabase(cookie.name);
419
478
  }
420
479
  }
@@ -423,65 +482,6 @@ function clearRevokedCookies(consent, options = {}) {
423
482
  return consent.subscribe(clear);
424
483
  }
425
484
  //#endregion
426
- //#region src/integrations/google-consent-mode.ts
427
- /** The standard mapping of Google's signals onto the fixed categories — the default. */
428
- const DEFAULT_GOOGLE_CONSENT_MAPPING = {
429
- ad_storage: "marketing",
430
- ad_user_data: "marketing",
431
- ad_personalization: "marketing",
432
- analytics_storage: "statistics",
433
- functionality_storage: "preferences",
434
- personalization_storage: "preferences",
435
- security_storage: "necessary"
436
- };
437
- function resolveGtag() {
438
- if (typeof window === "undefined") return void 0;
439
- const w = window;
440
- if (typeof w.gtag === "function") return w.gtag;
441
- w.dataLayer = w.dataLayer ?? [];
442
- const dataLayer = w.dataLayer;
443
- w.gtag = function gtag() {
444
- dataLayer.push(arguments);
445
- };
446
- return w.gtag;
447
- }
448
- /**
449
- * Wire a consent instance to Google Consent Mode v2: sends `gtag('consent', 'default', …)` with every
450
- * mapped signal denied (signals mapped to required categories granted), then an `update` with the
451
- * visitor's decision — immediately when one is stored, and again on every change.
452
- *
453
- * Call it **before** the Google tag (gtag.js / GTM) loads, so the default is in place for its first
454
- * hit. Returns an unsubscribe. A no-op on the server.
455
- */
456
- function googleConsentMode(consent, options = {}) {
457
- const gtag = options.gtag ?? resolveGtag();
458
- if (!gtag) return () => {};
459
- const entries = Object.entries(options.mapping ?? DEFAULT_GOOGLE_CONSENT_MAPPING);
460
- const signals = (isGranted) => {
461
- const out = {};
462
- for (const [signal, cat] of entries) out[signal] = (typeof cat === "string" ? [cat] : cat).every(isGranted) ? "granted" : "denied";
463
- return out;
464
- };
465
- if (options.adsDataRedaction) gtag("set", "ads_data_redaction", true);
466
- if (options.urlPassthrough) gtag("set", "url_passthrough", true);
467
- gtag("consent", "default", {
468
- ...signals((id) => consent.isRequired(id)),
469
- wait_for_update: options.waitForUpdate ?? 500,
470
- ...options.region ? { region: [...options.region] } : {}
471
- });
472
- let last = "";
473
- const sync = () => {
474
- if (consent.getSnapshot().status !== "decided" && last === "") return;
475
- const next = signals((id) => consent.isGranted(id));
476
- const key = JSON.stringify(next);
477
- if (key === last) return;
478
- last = key;
479
- gtag("consent", "update", next);
480
- };
481
- sync();
482
- return consent.subscribe(sync);
483
- }
484
- //#endregion
485
485
  //#region src/integrations/unblock-scripts.ts
486
486
  /**
487
487
  * Hold third-party scripts and embeds back until their category is granted — mark them up blocked and
@@ -554,18 +554,16 @@ function unblockScripts(consent, options = {}) {
554
554
  };
555
555
  }
556
556
  //#endregion
557
- exports.CONSENT_CATEGORIES = require_errors.CONSENT_CATEGORIES;
557
+ exports.CONSENT_CATEGORIES = require_machine_names.CONSENT_CATEGORIES;
558
558
  exports.ConsentCookieFormatter = ConsentCookieFormatter;
559
559
  exports.ConsentDecision = ConsentDecision;
560
- exports.ConsentError = require_errors.ConsentError;
561
- exports.DEFAULT_GOOGLE_CONSENT_MAPPING = DEFAULT_GOOGLE_CONSENT_MAPPING;
560
+ exports.ConsentError = require_machine_names.ConsentError;
562
561
  exports.DEFAULT_MAX_AGE = DEFAULT_MAX_AGE;
563
562
  exports.DEFAULT_STORAGE_KEY = DEFAULT_STORAGE_KEY;
564
- exports.REQUIRED_CATEGORY = require_errors.REQUIRED_CATEGORY;
563
+ exports.REQUIRED_CATEGORY = require_machine_names.REQUIRED_CATEGORY;
565
564
  exports.clearRevokedCookies = clearRevokedCookies;
566
565
  exports.createConsent = createConsent;
567
- exports.googleConsentMode = googleConsentMode;
568
- exports.isConsentCategoryId = require_errors.isConsentCategoryId;
566
+ exports.isConsentCategoryId = require_machine_names.isConsentCategoryId;
569
567
  exports.unblockScripts = unblockScripts;
570
568
 
571
569
  //# sourceMappingURL=index.cjs.map