@jini-ai/cookie-consent 0.7.2 → 0.7.3-next.1

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
@@ -119,4 +119,4 @@ An engine parity block is always added after the owner's CSS. `compileConsentCss
119
119
 
120
120
  ## Size
121
121
 
122
- `dist/client.min.js` owns state and the live context request; `dist/extensions.min.js` owns the banner binding, declared-script loading and bridges. Each asset retains the 4,608-byte gzip ceiling, and the build prints both measured sizes. At this revision they are approximately 4.5 KB and 1.8 KB gzipped. Serve both for the built-in banner or declarations; a headless ESM host may import only the pieces it uses.
122
+ `dist/client.min.js` owns state and the live context request; `dist/extensions.min.js` owns the banner binding, declared-script loading and bridges. The extensions asset keeps a 4,608-byte gzip ceiling and the client asset 4,672 bytes (it also hands each adapter call the storage purge); the build prints both measured sizes. At this revision they are approximately 4.5 KB and 1.8 KB gzipped. Serve both for the built-in banner or declarations; a headless ESM host may import only the pieces it uses.
@@ -1,28 +1,41 @@
1
1
  import { type Choices, type ConsentState, type JiniConsentApi, type Optional, type StoragePrefixes } from '../contract.js';
2
2
  /** @complexity O(cookie header). Malformed escapes read as "no value", never throw. */
3
- export declare function readCookie(doc: Document, name: string): string | null;
4
- export declare function writeCookie(doc: Document, { name, value, maxAgeS }: {
3
+ export declare function readCookie({ doc, name }: {
4
+ doc: Document;
5
+ name: string;
6
+ }, _optional?: Record<string, never>): string | null;
7
+ export declare function writeCookie({ doc, name, value, maxAgeS }: {
8
+ doc: Document;
5
9
  name: string;
6
10
  value: string;
7
11
  maxAgeS: number;
8
12
  }, { domain }?: {
9
13
  domain?: string | undefined;
10
14
  }): void;
11
- /** Expire prefixed cookies and local-storage keys; storage access can throw in sandboxes. @complexity O(cookies + keys). */
12
- export declare function purge(doc: Document, storage?: StoragePrefixes): void;
15
+ /** Expire prefixed cookies and local-storage keys; storage access can throw in sandboxes. Delete only the caller's storage
16
+ * prefixes; blocked localStorage is tolerated. This is also the `purge` handed to adapters (`PurgeStorage`).
17
+ * @example purgeStorage({ doc: document, storage: { cookies: ['vendor_'], local: ['vendor_'] } })
18
+ * @complexity O(cookies + local keys), O(keys) temporary space; no new identity or network. */
19
+ export declare function purgeStorage({ doc, storage }: {
20
+ doc: Document;
21
+ storage?: StoragePrefixes | undefined;
22
+ }, _optional?: {}): void;
13
23
  /** Allowed inert tags become live, in authored order (async=false). Unknown labels stay inert.
14
24
  * @complexity O(inert tags). */
15
- export declare function activateInert(doc: Document, { allowed, ran }: {
25
+ export declare function activateInert({ doc, allowed, ran }: {
26
+ doc: Document;
16
27
  allowed: Choices;
17
28
  ran: Set<Optional>;
18
- }): void;
29
+ }, _optional?: Record<string, never>): void;
19
30
  /** Footer links and the reopen button work for every banner mode, including "My own". */
20
31
  export declare function installOpeners({ api, doc }: {
21
32
  api: JiniConsentApi;
22
33
  doc: Document;
23
- }): void;
34
+ }, _optional?: Record<string, never>): void;
24
35
  /** A durable grant that is still waiting for its receipt keeps the banner open with its alert. */
25
- export declare const waiting: (s: ConsentState) => boolean;
36
+ export declare const waiting: ({ state }: {
37
+ state: ConsentState;
38
+ }, _optional?: Record<string, never>) => boolean;
26
39
  /** Wire #jini-consent (renderBanner's markup) to the public API. @complexity O(1) per click. */
27
40
  export declare function bindBanner({ api, doc }: {
28
41
  api: JiniConsentApi;
@@ -6,7 +6,7 @@ const SKIP = ['type', 'data-src', 'data-type', 'data-consent-category'];
6
6
  // Not <html>: the client sets html[data-consent-open] while the banner shows, and every click's closest() would hit it.
7
7
  const OPENERS = ':not(html)[data-consent-open],a[href="#privacy-choices"]';
8
8
  /** @complexity O(cookie header). Malformed escapes read as "no value", never throw. */
9
- export function readCookie(doc, name) {
9
+ export function readCookie({ doc, name }, _optional = {}) {
10
10
  const part = doc.cookie.split(/;\s*/).find(p => p.startsWith(name + '='));
11
11
  try {
12
12
  return part ? decodeURIComponent(part.slice(name.length + 1)) : null;
@@ -15,7 +15,7 @@ export function readCookie(doc, name) {
15
15
  return null;
16
16
  }
17
17
  }
18
- export function writeCookie(doc, { name, value, maxAgeS }, { domain } = {}) {
18
+ export function writeCookie({ doc, name, value, maxAgeS }, { domain } = {}) {
19
19
  const secure = doc.defaultView?.location.protocol === 'https:' ? '; Secure' : '';
20
20
  doc.cookie = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${Math.floor(maxAgeS)}; SameSite=Lax${secure}` + (domain ? '; Domain=' + domain : '');
21
21
  }
@@ -27,8 +27,11 @@ function expireEverywhere(doc, name) {
27
27
  for (let i = 0; i < parts.length - 1; i++)
28
28
  doc.cookie = `${expired}; Domain=.${parts.slice(i).join('.')}`;
29
29
  }
30
- /** Expire prefixed cookies and local-storage keys; storage access can throw in sandboxes. @complexity O(cookies + keys). */
31
- export function purge(doc, storage) {
30
+ /** Expire prefixed cookies and local-storage keys; storage access can throw in sandboxes. Delete only the caller's storage
31
+ * prefixes; blocked localStorage is tolerated. This is also the `purge` handed to adapters (`PurgeStorage`).
32
+ * @example purgeStorage({ doc: document, storage: { cookies: ['vendor_'], local: ['vendor_'] } })
33
+ * @complexity O(cookies + local keys), O(keys) temporary space; no new identity or network. */
34
+ export function purgeStorage({ doc, storage }, _optional = {}) {
32
35
  if (!storage)
33
36
  return;
34
37
  for (const part of doc.cookie.split(/;\s*/)) {
@@ -48,7 +51,7 @@ export function purge(doc, storage) {
48
51
  // Follow-up (P4): delete the cms runtime once the consumer inserts this client.
49
52
  /** Allowed inert tags become live, in authored order (async=false). Unknown labels stay inert.
50
53
  * @complexity O(inert tags). */
51
- export function activateInert(doc, { allowed, ran }) {
54
+ export function activateInert({ doc, allowed, ran }, _optional = {}) {
52
55
  // One category guard handles legacy tags and CMS templates, including unlabelled resources.
53
56
  doc.querySelectorAll('script[type="text/plain"],iframe[data-src],template[data-jini-consent-resource]').forEach(node => {
54
57
  const content = node.content;
@@ -83,7 +86,7 @@ function liveScript(doc, inert) {
83
86
  return s;
84
87
  }
85
88
  /** Footer links and the reopen button work for every banner mode, including "My own". */
86
- export function installOpeners({ api, doc }) {
89
+ export function installOpeners({ api, doc }, _optional = {}) {
87
90
  doc.addEventListener('click', event => {
88
91
  if (!event.target.closest?.(OPENERS))
89
92
  return;
@@ -110,7 +113,7 @@ function syncInputs(root, s) {
110
113
  }
111
114
  }
112
115
  /** A durable grant that is still waiting for its receipt keeps the banner open with its alert. */
113
- export const waiting = (s) => OPTIONAL.some(c => s.choices[c] && !s.allowed[c]);
116
+ export const waiting = ({ state }, _optional = {}) => OPTIONAL.some(c => state.choices[c] && !state.allowed[c]);
114
117
  /** Wire #jini-consent (renderBanner's markup) to the public API. @complexity O(1) per click. */
115
118
  export function bindBanner({ api, doc }) {
116
119
  const root = doc.getElementById('jini-consent');
@@ -120,8 +123,8 @@ export function bindBanner({ api, doc }) {
120
123
  const show = (open) => { root.hidden = !open; api.setOpen({ open }); };
121
124
  const settle = (s) => {
122
125
  if (alert)
123
- alert.hidden = !waiting(s);
124
- if (!waiting(s))
126
+ alert.hidden = !waiting({ state: s });
127
+ if (!waiting({ state: s }))
125
128
  show(false);
126
129
  };
127
130
  root.addEventListener('click', event => {
@@ -134,7 +137,7 @@ export function bindBanner({ api, doc }) {
134
137
  root.addEventListener('keydown', event => { if (event.key === 'Escape' && api.get().status === 'set')
135
138
  show(false); });
136
139
  doc.addEventListener(OPEN_EVENT, () => { syncInputs(root, api.get()); show(true); root.querySelector('button')?.focus(); });
137
- api.subscribe({ listener: s => { syncInputs(root, s); if (alert && !alert.hidden && !waiting(s))
140
+ api.subscribe({ listener: s => { syncInputs(root, s); if (alert && !alert.hidden && !waiting({ state: s }))
138
141
  settle(s); } });
139
142
  syncInputs(root, api.get());
140
143
  show(api.get().status === 'pending');
@@ -3,5 +3,5 @@
3
3
  * host that wants a headless-only build calls boot() from ./client without bindBanner.) */
4
4
  import { bindBanner } from './dom.js';
5
5
  import { boot } from './index.js';
6
- boot(window, { bindBanner });
6
+ boot({ win: window }, { bindBanner });
7
7
  //# sourceMappingURL=entry.js.map
@@ -1,10 +1,13 @@
1
1
  /** Full ESM client surface. The browser assets split optional feature delivery from core state. */
2
2
  import type { JiniConsentApi } from '../contract.js';
3
3
  import { createCookieConsent as createCore, type BootOptions } from './runtime.js';
4
- export { browserPorts, purgeStorage, installOpeners, bindBanner } from './runtime.js';
4
+ export { browserPorts, installOpeners, bindBanner } from './runtime.js';
5
+ export { purgeStorage } from './dom.js';
5
6
  export type { ClientPorts, ClientOptions, BootOptions } from './runtime.js';
6
7
  export declare const createCookieConsent: typeof createCore;
7
- export declare function boot(win?: Window & typeof globalThis, options?: BootOptions): JiniConsentApi | undefined;
8
+ export declare function boot({ win }?: {
9
+ win?: Window & typeof globalThis;
10
+ }, options?: BootOptions): JiniConsentApi | undefined;
8
11
  export declare function bootWithContext({ win }: {
9
12
  win: Window & typeof globalThis;
10
13
  }, options?: BootOptions): Promise<JiniConsentApi | undefined>;
@@ -1,18 +1,19 @@
1
1
  import { createCookieConsent as createCore, boot as bootCore, bootWithContext as bootCoreWithContext, readPage } from './runtime.js';
2
2
  import { installFeatures } from './features.js';
3
- export { browserPorts, purgeStorage, installOpeners, bindBanner } from './runtime.js';
4
- export const createCookieConsent = (required, options) => {
3
+ export { browserPorts, installOpeners, bindBanner } from './runtime.js';
4
+ export { purgeStorage } from './dom.js';
5
+ export const createCookieConsent = (required, options = {}) => {
5
6
  const api = createCore(required, options);
6
7
  installFeatures({ api, doc: required.ports.doc, config: required.config, reload: required.ports.reload });
7
8
  return api;
8
9
  };
9
10
  function features(win, api, options) {
10
11
  if (api)
11
- installFeatures({ api, doc: win.document, config: readPage(win.document), reload: options.ports?.reload ?? (() => win.location.reload()) }, { bindBanner: options.bindBanner });
12
+ installFeatures({ api, doc: win.document, config: readPage({ doc: win.document }), reload: options.ports?.reload ?? (() => win.location.reload()) }, { bindBanner: options.bindBanner });
12
13
  return api;
13
14
  }
14
- export function boot(win = window, options = {}) {
15
- return features(win, bootCore(win, { ...options, bindBanner: undefined }), options);
15
+ export function boot({ win = window } = {}, options = {}) {
16
+ return features(win, bootCore({ win }, { ...options, bindBanner: undefined }), options);
16
17
  }
17
18
  export async function bootWithContext({ win }, options = {}) {
18
19
  return features(win, await bootCoreWithContext({ win }, { ...options, bindBanner: undefined }), options);
@@ -2,7 +2,7 @@
2
2
  * receipts. Denial is applied before any network; a durable grant runs only once its receipt exists; a
3
3
  * response never sets a cookie, so a slow Accept can't overwrite a newer Reject. No polling, and no reload
4
4
  * unless something already ran that cannot be stopped (a raw inert script, or an adapter that can't revoke). */
5
- import { type ClientConfig, type ConsentAdapter, type Evidence, type JiniConsentApi, type PageConfig, type PluginRegistry, type StoragePrefixes } from '../contract.js';
5
+ import { type ClientConfig, type ConsentAdapter, type Evidence, type JiniConsentApi, type PageConfig, type PluginRegistry } from '../contract.js';
6
6
  export interface ClientPorts {
7
7
  doc: Document;
8
8
  fetch: typeof fetch;
@@ -17,12 +17,14 @@ export interface ClientOptions {
17
17
  plugins?: PluginRegistry;
18
18
  evidence?: Evidence | undefined;
19
19
  }
20
- /** @example createCookieConsent({ config, ports: browserPorts(window) }, { evidence: { mode: 'local' } }) */
20
+ /** @example createCookieConsent({ config, ports: browserPorts({ win: window }) }, { evidence: { mode: 'local' } }) */
21
21
  export declare function createCookieConsent({ config, ports }: {
22
22
  config: ClientConfig;
23
23
  ports: ClientPorts;
24
24
  }, options?: ClientOptions): JiniConsentApi;
25
- export declare function browserPorts(win: Window & typeof globalThis): ClientPorts;
25
+ export declare function browserPorts({ win }: {
26
+ win: Window & typeof globalThis;
27
+ }, _optional?: Record<string, never>): ClientPorts;
26
28
  export interface BootOptions {
27
29
  ports?: ClientPorts;
28
30
  /** Optional ESM-host banner binding; the shipped browser core leaves UI bindings to extensions.min.js. */
@@ -31,21 +33,18 @@ export interface BootOptions {
31
33
  doc: Document;
32
34
  }) => void) | undefined;
33
35
  }
34
- export declare function readPage(doc: Document): PageConfig | null;
36
+ export declare function readPage({ doc }: {
37
+ doc: Document;
38
+ }, _optional?: Record<string, never>): PageConfig | null;
35
39
  /** Reads #jini-consent-config, installs window.jiniConsent, drains and replaces the pre-boot queue.
36
40
  * A missing or broken config installs nothing, so nothing optional can run (fail closed). */
37
- export declare function boot(win?: Window & typeof globalThis, { ports, bindBanner }?: BootOptions): JiniConsentApi | undefined;
41
+ export declare function boot({ win }?: {
42
+ win?: Window & typeof globalThis;
43
+ }, { ports, bindBanner }?: BootOptions): JiniConsentApi | undefined;
38
44
  /** One fresh published-context read before cookie access. Shared cached HTML contains no visitor state.
39
45
  * Missing/disabled config and failed context install nothing; no polling or storage reads. */
40
46
  export declare function bootWithContext({ win }: {
41
47
  win: Window & typeof globalThis;
42
48
  }, options?: BootOptions): Promise<JiniConsentApi | undefined>;
43
- /** Delete only the caller's storage prefixes; blocked localStorage is tolerated.
44
- * @example purgeStorage({ doc: document, storage: { cookies: ['vendor_'], local: ['vendor_'] } })
45
- * @complexity O(cookies + local keys), O(keys) temporary space; no new identity or network. */
46
- export declare function purgeStorage({ doc, storage }: {
47
- doc: Document;
48
- storage: StoragePrefixes;
49
- }, _optional?: {}): void;
50
49
  export { bindBanner, installOpeners } from './dom.js';
51
50
  //# sourceMappingURL=runtime.d.ts.map
@@ -6,14 +6,14 @@ import { ADAPTER_KIND, CONFIG_ID, CONSENT_COOKIE, OPEN_EVENT, OPTIONAL, READY_EV
6
6
  import { choicesFor, DAY_MS, effective, parseStored, RECEIPT_ID, regionFrom } from '../contracts/policy.js';
7
7
  import { allows } from '../contracts/scripts.js';
8
8
  import { ADAPTER_SLOT, createPluginRegistry } from '../contracts/plugins.js';
9
- import { activateInert, installOpeners, purge, readCookie, waiting, writeCookie } from './dom.js';
9
+ import { activateInert, installOpeners, purgeStorage, readCookie, waiting, writeCookie } from './dom.js';
10
10
  const within = (p, ms) => Promise.race([p, new Promise(r => setTimeout(r, ms))]);
11
11
  const quiet = (fn) => { try {
12
12
  fn();
13
13
  }
14
14
  catch { /* a broken plugin or listener never blocks consent */ } };
15
15
  const durableEvidence = (evidence) => evidence?.mode === 'durable' ? evidence : null;
16
- /** @example createCookieConsent({ config, ports: browserPorts(window) }, { evidence: { mode: 'local' } }) */
16
+ /** @example createCookieConsent({ config, ports: browserPorts({ win: window }) }, { evidence: { mode: 'local' } }) */
17
17
  export function createCookieConsent({ config, ports }, options = {}) {
18
18
  const { doc } = ports;
19
19
  const plugins = options.plugins ?? createPluginRegistry({}, { slots: [ADAPTER_SLOT] });
@@ -23,8 +23,8 @@ export function createCookieConsent({ config, ports }, options = {}) {
23
23
  const ran = new Set(); // categories whose raw inert tags executed
24
24
  const anonymous = config.banner === 'off';
25
25
  const maxAgeMs = (config.maxAgeDays ?? 180) * DAY_MS;
26
- const region = regionFrom({ configured: config.regionMode, hint: anonymous ? null : readCookie(doc, REGION_COOKIE) });
27
- const fromCookie = () => anonymous ? null : parseStored({ raw: readCookie(doc, CONSENT_COOKIE) });
26
+ const region = regionFrom({ configured: config.regionMode, hint: anonymous ? null : readCookie({ doc, name: REGION_COOKIE }) });
27
+ const fromCookie = () => anonymous ? null : parseStored({ raw: readCookie({ doc, name: CONSENT_COOKIE }) });
28
28
  let stored = fromCookie();
29
29
  let cookiePersisted = true;
30
30
  let state = compute();
@@ -33,8 +33,8 @@ export function createCookieConsent({ config, ports }, options = {}) {
33
33
  }
34
34
  function persist() {
35
35
  const value = JSON.stringify(stored);
36
- writeCookie(doc, { name: CONSENT_COOKIE, value, maxAgeS: maxAgeMs / 1000 }, { domain: config.cookieDomain });
37
- cookiePersisted = readCookie(doc, CONSENT_COOKIE) === value;
36
+ writeCookie({ doc, name: CONSENT_COOKIE, value, maxAgeS: maxAgeMs / 1000 }, { domain: config.cookieDomain });
37
+ cookiePersisted = readCookie({ doc, name: CONSENT_COOKIE }) === value;
38
38
  }
39
39
  /** Off-mode adapters load for identity cleanup even at none; only permitted levels grant.
40
40
  * Abort is checked after the import and handed to grant(), so a withdrawal during either wait wins. */
@@ -43,10 +43,10 @@ export function createCookieConsent({ config, ports }, options = {}) {
43
43
  const ctl = new AbortController();
44
44
  const load = Promise.resolve(slot.adapter ?? ports.importModule(slot.entry.src).then(m => (slot.adapter = m.default)));
45
45
  const result = load.then(adapter => {
46
- quiet(() => adapter.onState?.({ state }));
46
+ quiet(() => adapter.onState?.({ state, purge: purgeStorage }));
47
47
  if (ctl.signal.aborted || anonymous && state.analyticsLevel === 'none')
48
48
  return null; // withdrawn first: nothing ran
49
- return Promise.resolve().then(() => adapter.grant({ config: slot.entry.config ?? adapter.config, state, signal: ctl.signal }))
49
+ return Promise.resolve().then(() => adapter.grant({ config: slot.entry.config ?? adapter.config, state, signal: ctl.signal, purge: purgeStorage }))
50
50
  .then((r = {}) => r, () => ({})); // a grant that threw may have run code
51
51
  }, () => null); // import failed: nothing ran
52
52
  slot.run = { ctl, result };
@@ -63,7 +63,7 @@ export function createCookieConsent({ config, ports }, options = {}) {
63
63
  return false;
64
64
  const clean = await Promise.resolve().then(() => revoker.revoke?.()).catch(() => false);
65
65
  if (!anonymous && slot.generation === generation)
66
- purge(doc, slot.adapter?.storage ?? slot.entry.storage);
66
+ purgeStorage({ doc, storage: slot.adapter?.storage ?? slot.entry.storage });
67
67
  return !clean;
68
68
  }
69
69
  function reconcile(next) {
@@ -74,11 +74,11 @@ export function createCookieConsent({ config, ports }, options = {}) {
74
74
  start(slot);
75
75
  if (!allowed && slot.run)
76
76
  stops.push(stop(slot));
77
- quiet(() => slot.adapter?.onState?.({ state: next }));
77
+ quiet(() => slot.adapter?.onState?.({ state: next, purge: purgeStorage }));
78
78
  }
79
79
  // Raw tags cannot promise anonymous behavior; only declared adapters can.
80
80
  if (!anonymous)
81
- activateInert(doc, { allowed: next.allowed, ran });
81
+ activateInert({ doc, allowed: next.allowed, ran });
82
82
  const rawRevoked = OPTIONAL.some(c => ran.has(c) && !next.allowed[c]);
83
83
  void Promise.all(stops).then(dirty => { if (rawRevoked || dirty.includes(true))
84
84
  ports.reload(); });
@@ -120,7 +120,7 @@ export function createCookieConsent({ config, ports }, options = {}) {
120
120
  persist();
121
121
  const now = apply(); // denial is live here, before any network
122
122
  const sent = confirm(stored, previousId);
123
- if (durable && waiting(now))
123
+ if (durable && waiting({ state: now }))
124
124
  await within(sent, durable.waitMs ?? 1500);
125
125
  return state;
126
126
  }
@@ -132,8 +132,8 @@ export function createCookieConsent({ config, ports }, options = {}) {
132
132
  if (anonymous || state.allowed[entry.category])
133
133
  start(slot);
134
134
  else
135
- purge(doc, entry.storage); // leftovers of an expired or withdrawn choice
136
- quiet(() => slot.adapter?.onState?.({ state })); // lazy adapters get state once loaded
135
+ purgeStorage({ doc, storage: entry.storage }); // leftovers of an expired or withdrawn choice
136
+ quiet(() => slot.adapter?.onState?.({ state, purge: purgeStorage })); // lazy adapters get state once loaded
137
137
  }
138
138
  function syncSlots(items) {
139
139
  const ids = new Set(items.map(i => i.id));
@@ -181,14 +181,14 @@ export function createCookieConsent({ config, ports }, options = {}) {
181
181
  void confirm(stored); // durable retry of an earlier failed receipt
182
182
  return api;
183
183
  }
184
- export function browserPorts(win) {
184
+ export function browserPorts({ win }, _optional = {}) {
185
185
  return {
186
186
  doc: win.document, fetch: win.fetch.bind(win), now: Date.now, reload: () => win.location.reload(),
187
187
  gpc: () => win.navigator.globalPrivacyControl === true || win.navigator.doNotTrack === '1',
188
188
  importModule: src => import(/* @vite-ignore */ src),
189
189
  };
190
190
  }
191
- export function readPage(doc) {
191
+ export function readPage({ doc }, _optional = {}) {
192
192
  try {
193
193
  return JSON.parse(doc.getElementById(CONFIG_ID)?.textContent ?? '');
194
194
  }
@@ -198,16 +198,16 @@ export function readPage(doc) {
198
198
  }
199
199
  /** Reads #jini-consent-config, installs window.jiniConsent, drains and replaces the pre-boot queue.
200
200
  * A missing or broken config installs nothing, so nothing optional can run (fail closed). */
201
- export function boot(win = window, { ports = browserPorts(win), bindBanner } = {}) {
201
+ export function boot({ win = window } = {}, { ports = browserPorts({ win }), bindBanner } = {}) {
202
202
  if (win.jiniConsent)
203
203
  return win.jiniConsent;
204
204
  const doc = win.document;
205
- const page = readPage(doc);
205
+ const page = readPage({ doc });
206
206
  if (!page)
207
207
  return undefined;
208
208
  return installPage(win, page, { ports, bindBanner });
209
209
  }
210
- function installPage(win, page, { ports = browserPorts(win), bindBanner }) {
210
+ function installPage(win, page, { ports = browserPorts({ win }), bindBanner }) {
211
211
  // The parsed page already satisfies ClientConfig; avoid copying it just to omit evidence.
212
212
  const doc = win.document;
213
213
  const api = createCookieConsent({ config: page, ports }, { evidence: page.evidence });
@@ -227,12 +227,12 @@ function installPage(win, page, { ports = browserPorts(win), bindBanner }) {
227
227
  export async function bootWithContext({ win }, options = {}) {
228
228
  if (win.jiniConsent)
229
229
  return win.jiniConsent;
230
- const page = readPage(win.document);
230
+ const page = readPage({ doc: win.document });
231
231
  if (!page || page.banner === 'off')
232
232
  return undefined;
233
233
  if (!page.context)
234
- return boot(win, options);
235
- const ports = options.ports ?? browserPorts(win);
234
+ return boot({ win }, options);
235
+ const ports = options.ports ?? browserPorts({ win });
236
236
  try {
237
237
  const context = await ports.fetch(page.context, { credentials: 'same-origin', cache: 'no-store' })
238
238
  .then(response => response.ok ? response.json() : null);
@@ -265,11 +265,5 @@ function validContext(value) {
265
265
  const context = value;
266
266
  return context?.enabled === true && typeof context.policy === 'string' && ['auto', 'opt-in', 'opt-out'].includes(String(context.regionMode));
267
267
  }
268
- /** Delete only the caller's storage prefixes; blocked localStorage is tolerated.
269
- * @example purgeStorage({ doc: document, storage: { cookies: ['vendor_'], local: ['vendor_'] } })
270
- * @complexity O(cookies + local keys), O(keys) temporary space; no new identity or network. */
271
- export function purgeStorage({ doc, storage }, _optional = {}) {
272
- purge(doc, storage);
273
- }
274
268
  export { bindBanner, installOpeners } from './dom.js';
275
269
  //# sourceMappingURL=runtime.js.map
@@ -1 +1 @@
1
- "use strict";(()=>{var P="jini_choices",K="jini_region",H="jini:consent",J="jini:consent-ready",T="jini:consent-open",B="jini-consent-config",h=["functional","analytics","marketing"],G=["necessary",...h],V=["accept","reject","save","do-not-sell","withdraw"];var k="consent-adapter";var D=864e5,pe=180*D,fe=6e4,I=/^[\w-]{16,128}$/,W=Object.freeze({necessary:!0,functional:!1,analytics:!1,marketing:!1});function $({configured:e,hint:t},n={}){return e!=="auto"?e:t==="us"?"opt-out":"opt-in"}var A=(e,t=e,n=t)=>({functional:e,analytics:t,marketing:n});function z({action:e,picked:t={}},n={}){return e==="accept"?A(!0):e==="save"?A(t.functional===!0,t.analytics===!0,t.marketing===!0):e==="do-not-sell"?A(t.functional!==!1,!1):A(!1)}function ge({flags:e,gpc:t},n={}){return{necessary:!0,functional:e.functional,analytics:e.analytics&&!t,marketing:e.marketing&&!t}}function U({stored:e,policy:t,region:n,gpc:o,nowMs:r},{maxAgeMs:a=pe,durable:m=!1,anonymous:C=!1}={}){let g=!C&&e&&e.p===t&&e.t<=r+fe&&r-e.t<=a?e:null,y=ge({flags:C?W:g?.c??A(n==="opt-out"),gpc:o}),v={contract:1,policy:t,region:n,gpc:o,choices:y,...ye({choices:y,live:g,durable:m,anonymous:C,gpc:o})};return g?{...v,status:"set",action:g.a,at:g.t,receipt:me(g)}:{...v,status:"pending",action:null,at:null,receipt:"none"}}function ye({choices:e,live:t,durable:n,anonymous:o,gpc:r},a={}){let m=t&&n&&!t.r,C=o||m?W:e,g=C.analytics?"full":"none";return{allowed:C,analyticsLevel:o&&!r?"anonymous":g}}function me(e){return e.r?"stored":e.q?"pending":"local"}function Q({raw:e},t={}){if(!e||e.length>1024)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!Ce(n))return null;let o={v:1,p:n.p,c:A(n.c.functional,n.c.analytics,n.c.marketing),t:n.t,a:n.a};return typeof n.r=="string"&&I.test(n.r)&&(o.r=n.r),n.q===1&&(o.q=1),o}function Ce(e){return!e||e.v!==1||typeof e.p!="string"||!Number.isFinite(e.t)?!1:V.includes(e.a)&&be(e.c)}function be(e){let t=e;return!t||typeof t!="object"?!1:["functional","analytics","marketing"].every(n=>Object.hasOwn(t,n)&&typeof t[n]=="boolean")}function Y({state:e,consent:t=[]},n={}){return t.every(o=>G.includes(o)&&e.allowed[o]===!0)}var Se=/^[a-z0-9][a-z0-9._:-]{0,63}$/;function X(e={},{slots:t=[],onProblem:n=()=>{}}={}){let o=new Map,r=[],a=new Set,m=new Set,C=s=>r.filter(c=>c.kind===s).sort((c,l)=>l.priority-c.priority).map(c=>c.value),g=s=>m.forEach(c=>{if(c.kind===s)try{c.fn(C(s))}catch{}});function y(s,c){let l=S=>(n({id:String(s.id),kind:s.kind,reason:S,...c.source?{source:c.source}:{}}),()=>{});if(!Se.test(String(s.id)))return l("short lowercase id");let x=o.get(s.kind).accept({contribution:s});if(typeof x=="string")return l(x);if(r.some(S=>S.kind===s.kind&&S.id===s.id))return l("duplicate id");let b={kind:s.kind,id:s.id,value:x,priority:c.priority??0};return r.push(b),g(s.kind),()=>{let S=r.indexOf(b);S>=0&&(r.splice(S,1),g(s.kind))}}let v={defineSlot({slot:s}){if(!o.has(s.kind)){o.set(s.kind,s);for(let c of a)c.raw.kind===s.kind&&(a.delete(c),c.dispose=y(c.raw,c.options))}},registerPlugin(s,c={}){if(o.has(s.kind))return y(s,c);let l={raw:s,options:c,dispose:()=>{a.delete(l)}};return a.add(l),()=>l.dispose()},list:({kind:s})=>C(s),subscribe({kind:s,listener:c}){let l={kind:s,fn:c};return m.add(l),()=>{m.delete(l)}}};for(let s of t)v.defineSlot({slot:s});return v}var Z={kind:k,accept({contribution:e}){return h.includes(e.category)?typeof e.grant=="function"||typeof e.src=="string"?e:"grant() or src needed":"category must be functional, analytics or marketing"}};var ve=["type","data-src","data-type","data-consent-category"],he=':not(html)[data-consent-open],a[href="#privacy-choices"]';function R(e,t){let n=e.cookie.split(/;\s*/).find(o=>o.startsWith(t+"="));try{return n?decodeURIComponent(n.slice(t.length+1)):null}catch{return null}}function ee(e,{name:t,value:n,maxAgeS:o},{domain:r}={}){let a=e.defaultView?.location.protocol==="https:"?"; Secure":"";e.cookie=`${t}=${encodeURIComponent(n)}; Path=/; Max-Age=${Math.floor(o)}; SameSite=Lax${a}`+(r?"; Domain="+r:"")}function xe(e,t){let n=(e.defaultView?.location.hostname??"").split("."),o=`${t}=; Path=/; Max-Age=0`;e.cookie=o;for(let r=0;r<n.length-1;r++)e.cookie=`${o}; Domain=.${n.slice(r).join(".")}`}function M(e,t){if(t){for(let n of e.cookie.split(/;\s*/)){let o=n.split("=")[0];t.cookies?.some(r=>o.startsWith(r))&&xe(e,o)}try{let n=e.defaultView.localStorage;for(let o of Object.keys(n))t.local?.some(r=>o.startsWith(r))&&n.removeItem(o)}catch{}}}function te(e,{allowed:t,ran:n}){e.querySelectorAll('script[type="text/plain"],iframe[data-src],template[data-jini-consent-resource]').forEach(o=>{let r=o.content,a=r?o.dataset.category:o.dataset.consentCategory;!h.includes(a)||!t[a]||(n.add(a),o.tagName==="IFRAME"?(o.src=o.dataset.src,o.removeAttribute("data-src")):o.replaceWith(r??Ae(e,o)))})}function Ae(e,t){let n=e.createElement("script");for(let{name:o,value:r}of t.attributes)ve.includes(o)||n.setAttribute(o,r);return t.nonce&&(n.nonce=t.nonce),t.dataset.type&&(n.type=t.dataset.type),t.dataset.src?n.src=t.dataset.src:n.text=t.text,n.async=!1,n}function ne({api:e,doc:t}){t.addEventListener("click",n=>{n.target.closest?.(he)&&(n.preventDefault(),e.open())})}var oe=e=>h.some(t=>e.choices[t]&&!e.allowed[t]);var Ee=(e,t)=>Promise.race([e,new Promise(n=>setTimeout(n,t))]),O=e=>{try{e()}catch{}},ke=e=>e?.mode==="durable"?e:null;function Pe({config:e,ports:t},n={}){let{doc:o}=t,r=n.plugins??X({},{slots:[Z]}),a=ke(n.evidence),m=new Map,C=new Set,g=new Set,y=e.banner==="off",v=(e.maxAgeDays??180)*D,s=$({configured:e.regionMode,hint:y?null:R(o,K)}),c=()=>y?null:Q({raw:R(o,P)}),l=c(),x=!0,b=S();function S(){return U({stored:l,policy:e.policy,region:s,gpc:t.gpc(),nowMs:t.now()},{maxAgeMs:v,durable:!!a,anonymous:y})}function _(){let i=JSON.stringify(l);ee(o,{name:P,value:i,maxAgeS:v/1e3},{domain:e.cookieDomain}),x=R(o,P)===i}function j(i){i.generation++;let u=new AbortController,d=Promise.resolve(i.adapter??t.importModule(i.entry.src).then(f=>i.adapter=f.default)).then(f=>(O(()=>f.onState?.({state:b})),u.signal.aborted||y&&b.analyticsLevel==="none"?null:Promise.resolve().then(()=>f.grant({config:i.entry.config??f.config,state:b,signal:u.signal})).then((de={})=>de,()=>({}))),()=>null);i.run={ctl:u,result:d}}async function L(i){let u=i.run,p=i.generation;i.run=void 0,u.ctl.abort();let d=await u.result;if(!d)return!1;let f=await Promise.resolve().then(()=>d.revoke?.()).catch(()=>!1);return!y&&i.generation===p&&M(o,i.adapter?.storage??i.entry.storage),!f}function ae(i){let u=[];for(let d of m.values()){let f=y?i.analyticsLevel==="anonymous":i.allowed[d.entry.category];f&&!d.run&&j(d),!f&&d.run&&u.push(L(d)),O(()=>d.adapter?.onState?.({state:i}))}y||te(o,{allowed:i.allowed,ran:g});let p=h.some(d=>g.has(d)&&!i.allowed[d]);Promise.all(u).then(d=>{(p||d.includes(!0))&&t.reload()})}function E(){let i=b=S(),u=o.documentElement;return u.dataset.consent=i.status,u.dataset.consentRegion=i.region,u.toggleAttribute("data-consent-gpc",i.gpc),ae(i),C.forEach(p=>O(()=>p(i))),o.dispatchEvent(new CustomEvent(H,{detail:i})),i}async function q(i,u){if(!a)return;let p=JSON.stringify({policy:i.p,choices:i.c,action:i.a,gpc:t.gpc(),previousId:u}),d=await t.fetch(a.endpoint,{method:"POST",credentials:"same-origin",keepalive:!0,headers:{"content-type":"application/json"},body:p}).catch(()=>null),f=d?.ok?await d.json().catch(()=>null):null;l!==i||w()||typeof f?.id!="string"||!I.test(f.id)||(l={...i,r:f.id},delete l.q,_(),E())}async function ce({action:i},{choices:u={}}={}){if(y)return E();let p=l?.r;l={v:1,p:e.policy,c:z({action:i,picked:u}),t:t.now(),a:i,...a?{q:1}:{}},_();let d=E(),f=q(l,p);return a&&oe(d)&&await Ee(f,a.waitMs??1500),b}function le(i){if(y&&(!i.supportsAnonymous||i.category!=="analytics"))return;let u={entry:i,generation:0,adapter:typeof i.grant=="function"?i:void 0};m.set(i.id,u),y||b.allowed[i.category]?j(u):M(o,i.storage),O(()=>u.adapter?.onState?.({state:b}))}function F(i){let u=new Set(i.map(p=>p.id));for(let[p,d]of m)u.has(p)||(m.delete(p),d.run&&L(d).then(f=>{f&&t.reload()}));for(let p of i)m.has(p.id)||le(p)}function w(){let i=c();return!i&&!x||["t","a","r"].every(u=>i?.[u]===l?.[u])?!1:(l=i,E(),!0)}let ue={contract:1,plugins:r,set:ce,get:()=>b,allows:({consent:i})=>Y({state:b,consent:i}),subscribe:({listener:i})=>(C.add(i),()=>{C.delete(i)}),open:()=>{o.dispatchEvent(new CustomEvent(T))},setOpen:({open:i})=>{o.documentElement.toggleAttribute("data-consent-open",i)}};return r.subscribe({kind:k,listener:F}),F(r.list({kind:k})),e.plugins?.forEach(i=>r.registerPlugin(i,{source:"page"})),E(),o.addEventListener("visibilitychange",()=>{o.visibilityState==="visible"&&w()}),o.defaultView?.addEventListener("pageshow",w),l?.q&&l.p===e.policy&&q(l),ue}function N(e){return{doc:e.document,fetch:e.fetch.bind(e),now:Date.now,reload:()=>e.location.reload(),gpc:()=>e.navigator.globalPrivacyControl===!0||e.navigator.doNotTrack==="1",importModule:t=>import(t)}}function ie(e){try{return JSON.parse(e.getElementById(B)?.textContent??"")}catch{return null}}function Re(e=window,{ports:t=N(e),bindBanner:n}={}){if(e.jiniConsent)return e.jiniConsent;let o=e.document,r=ie(o);if(r)return re(e,r,{ports:t,bindBanner:n})}function re(e,t,{ports:n=N(e),bindBanner:o}){let r=e.document,a=Pe({config:t,ports:n},{evidence:t.evidence}),m=Array.isArray(e.jiniConsentQueue)?e.jiniConsentQueue:[];return e.jiniConsent=a,e.jiniConsentQueue={push:(...C)=>C.forEach(g=>a.plugins.registerPlugin(g,{source:"queue"}))},e.jiniConsentQueue.push(...m),ne({api:a,doc:r}),t.banner==="jini"&&o?.({api:a,doc:r}),r.dispatchEvent(new CustomEvent(J,{detail:a})),a}async function se({win:e},t={}){if(e.jiniConsent)return e.jiniConsent;let n=ie(e.document);if(!n||n.banner==="off")return;if(!n.context)return Re(e,t);let o=t.ports??N(e);try{let r=await o.fetch(n.context,{credentials:"same-origin",cache:"no-store"}).then(a=>a.ok?a.json():null);if(!we(r))return;if(r.policy!==n.policy){Oe({win:e,policy:n.policy,reload:o.reload});return}return re(e,{...n,regionMode:r.regionMode},{...t,ports:o})}catch{return}}function Oe({win:e,policy:t,reload:n}){try{let o=`jini-consent-reload:${t}`;if(e.sessionStorage.getItem(o))return;e.sessionStorage.setItem(o,"1"),n()}catch{}}function we(e){let t=e;return t?.enabled===!0&&typeof t.policy=="string"&&["auto","opt-in","opt-out"].includes(String(t.regionMode))}se({win:window});})();
1
+ "use strict";(()=>{var R="jini_choices",K="jini_region",H="jini:consent",J="jini:consent-ready",D="jini:consent-open",B="jini-consent-config",h=["functional","analytics","marketing"],G=["necessary",...h],V=["accept","reject","save","do-not-sell","withdraw"];var P="consent-adapter";var I=864e5,W=180*I,fe=6e4,M=/^[\w-]{16,128}$/,$=Object.freeze({necessary:!0,functional:!1,analytics:!1,marketing:!1});function z({configured:e,hint:t},n={}){return e!=="auto"?e:t==="us"?"opt-out":"opt-in"}var E=(e,t=e,n=t)=>({functional:e,analytics:t,marketing:n});function U({action:e,picked:t={}},n={}){return e==="accept"?E(!0):e==="save"?E(t.functional===!0,t.analytics===!0,t.marketing===!0):e==="do-not-sell"?E(t.functional!==!1,!1):E(!1)}function ge({flags:e,gpc:t},n={}){return{necessary:!0,functional:e.functional,analytics:e.analytics&&!t,marketing:e.marketing&&!t}}function Q({stored:e,policy:t,region:n,gpc:o,nowMs:r},{maxAgeMs:s=W,durable:p=!1,anonymous:C=!1}={}){let y=ye({stored:e,policy:t,nowMs:r},{maxAgeMs:s,anonymous:C}),m=ge({flags:C?$:y?.c??E(n==="opt-out"),gpc:o}),v={contract:1,policy:t,region:n,gpc:o,choices:m,...me({choices:m,live:y,durable:p,anonymous:C,gpc:o})};return y?{...v,status:"set",action:y.a,at:y.t,receipt:Ce(y)}:{...v,status:"pending",action:null,at:null,receipt:"none"}}function ye({stored:e,policy:t,nowMs:n},{maxAgeMs:o=W,anonymous:r=!1}={}){return!r&&e&&e.p===t&&e.t<=n+fe&&n-e.t<=o?e:null}function me({choices:e,live:t,durable:n,anonymous:o,gpc:r},s={}){let p=t&&n&&!t.r,C=o||p?$:e,y=C.analytics?"full":"none";return{allowed:C,analyticsLevel:o&&!r?"anonymous":y}}function Ce(e){return e.r?"stored":e.q?"pending":"local"}function Y({raw:e},t={}){if(!e||e.length>1024)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!be(n))return null;let o={v:1,p:n.p,c:E(n.c.functional,n.c.analytics,n.c.marketing),t:n.t,a:n.a};return typeof n.r=="string"&&M.test(n.r)&&(o.r=n.r),n.q===1&&(o.q=1),o}function be(e){return!e||e.v!==1||typeof e.p!="string"||!Number.isFinite(e.t)?!1:V.includes(e.a)&&Se(e.c)}function Se(e){let t=e;return!t||typeof t!="object"?!1:["functional","analytics","marketing"].every(n=>Object.hasOwn(t,n)&&typeof t[n]=="boolean")}function X({state:e,consent:t=[]},n={}){return t.every(o=>G.includes(o)&&e.allowed[o]===!0)}var ve=/^[a-z0-9][a-z0-9._:-]{0,63}$/;function Z(e={},{slots:t=[],onProblem:n=()=>{}}={}){let o=new Map,r=[],s=new Set,p=new Set,C=a=>r.filter(c=>c.kind===a).sort((c,l)=>l.priority-c.priority).map(c=>c.value),y=a=>p.forEach(c=>{if(c.kind===a)try{c.fn(C(a))}catch{}});function m(a,c){let l=S=>(n({id:String(a.id),kind:a.kind,reason:S,...c.source?{source:c.source}:{}}),()=>{});if(!ve.test(String(a.id)))return l("short lowercase id");let A=o.get(a.kind).accept({contribution:a});if(typeof A=="string")return l(A);if(r.some(S=>S.kind===a.kind&&S.id===a.id))return l("duplicate id");let b={kind:a.kind,id:a.id,value:A,priority:c.priority??0};return r.push(b),y(a.kind),()=>{let S=r.indexOf(b);S>=0&&(r.splice(S,1),y(a.kind))}}let v={defineSlot({slot:a}){if(!o.has(a.kind)){o.set(a.kind,a);for(let c of s)c.raw.kind===a.kind&&(s.delete(c),c.dispose=m(c.raw,c.options))}},registerPlugin(a,c={}){if(o.has(a.kind))return m(a,c);let l={raw:a,options:c,dispose:()=>{s.delete(l)}};return s.add(l),()=>l.dispose()},list:({kind:a})=>C(a),subscribe({kind:a,listener:c}){let l={kind:a,fn:c};return p.add(l),()=>{p.delete(l)}}};for(let a of t)v.defineSlot({slot:a});return v}var ee={kind:P,accept({contribution:e}){return h.includes(e.category)?typeof e.grant=="function"||typeof e.src=="string"?e:"grant() or src needed":"category must be functional, analytics or marketing"}};var he=["type","data-src","data-type","data-consent-category"],xe=':not(html)[data-consent-open],a[href="#privacy-choices"]';function w({doc:e,name:t},n={}){let o=e.cookie.split(/;\s*/).find(r=>r.startsWith(t+"="));try{return o?decodeURIComponent(o.slice(t.length+1)):null}catch{return null}}function te({doc:e,name:t,value:n,maxAgeS:o},{domain:r}={}){let s=e.defaultView?.location.protocol==="https:"?"; Secure":"";e.cookie=`${t}=${encodeURIComponent(n)}; Path=/; Max-Age=${Math.floor(o)}; SameSite=Lax${s}`+(r?"; Domain="+r:"")}function Ae(e,t){let n=(e.defaultView?.location.hostname??"").split("."),o=`${t}=; Path=/; Max-Age=0`;e.cookie=o;for(let r=0;r<n.length-1;r++)e.cookie=`${o}; Domain=.${n.slice(r).join(".")}`}function x({doc:e,storage:t},n={}){if(t){for(let o of e.cookie.split(/;\s*/)){let r=o.split("=")[0];t.cookies?.some(s=>r.startsWith(s))&&Ae(e,r)}try{let o=e.defaultView.localStorage;for(let r of Object.keys(o))t.local?.some(s=>r.startsWith(s))&&o.removeItem(r)}catch{}}}function ne({doc:e,allowed:t,ran:n},o={}){e.querySelectorAll('script[type="text/plain"],iframe[data-src],template[data-jini-consent-resource]').forEach(r=>{let s=r.content,p=s?r.dataset.category:r.dataset.consentCategory;!h.includes(p)||!t[p]||(n.add(p),r.tagName==="IFRAME"?(r.src=r.dataset.src,r.removeAttribute("data-src")):r.replaceWith(s??Ee(e,r)))})}function Ee(e,t){let n=e.createElement("script");for(let{name:o,value:r}of t.attributes)he.includes(o)||n.setAttribute(o,r);return t.nonce&&(n.nonce=t.nonce),t.dataset.type&&(n.type=t.dataset.type),t.dataset.src?n.src=t.dataset.src:n.text=t.text,n.async=!1,n}function oe({api:e,doc:t},n={}){t.addEventListener("click",o=>{o.target.closest?.(xe)&&(o.preventDefault(),e.open())})}var ie=({state:e},t={})=>h.some(n=>e.choices[n]&&!e.allowed[n]);var ke=(e,t)=>Promise.race([e,new Promise(n=>setTimeout(n,t))]),O=e=>{try{e()}catch{}},Pe=e=>e?.mode==="durable"?e:null;function Re({config:e,ports:t},n={}){let{doc:o}=t,r=n.plugins??Z({},{slots:[ee]}),s=Pe(n.evidence),p=new Map,C=new Set,y=new Set,m=e.banner==="off",v=(e.maxAgeDays??180)*I,a=z({configured:e.regionMode,hint:m?null:w({doc:o,name:K})}),c=()=>m?null:Y({raw:w({doc:o,name:R})}),l=c(),A=!0,b=S();function S(){return Q({stored:l,policy:e.policy,region:a,gpc:t.gpc(),nowMs:t.now()},{maxAgeMs:v,durable:!!s,anonymous:m})}function N(){let i=JSON.stringify(l);te({doc:o,name:R,value:i,maxAgeS:v/1e3},{domain:e.cookieDomain}),A=w({doc:o,name:R})===i}function j(i){i.generation++;let u=new AbortController,d=Promise.resolve(i.adapter??t.importModule(i.entry.src).then(g=>i.adapter=g.default)).then(g=>(O(()=>g.onState?.({state:b,purge:x})),u.signal.aborted||m&&b.analyticsLevel==="none"?null:Promise.resolve().then(()=>g.grant({config:i.entry.config??g.config,state:b,signal:u.signal,purge:x})).then((pe={})=>pe,()=>({}))),()=>null);i.run={ctl:u,result:d}}async function L(i){let u=i.run,f=i.generation;i.run=void 0,u.ctl.abort();let d=await u.result;if(!d)return!1;let g=await Promise.resolve().then(()=>d.revoke?.()).catch(()=>!1);return!m&&i.generation===f&&x({doc:o,storage:i.adapter?.storage??i.entry.storage}),!g}function ce(i){let u=[];for(let d of p.values()){let g=m?i.analyticsLevel==="anonymous":i.allowed[d.entry.category];g&&!d.run&&j(d),!g&&d.run&&u.push(L(d)),O(()=>d.adapter?.onState?.({state:i,purge:x}))}m||ne({doc:o,allowed:i.allowed,ran:y});let f=h.some(d=>y.has(d)&&!i.allowed[d]);Promise.all(u).then(d=>{(f||d.includes(!0))&&t.reload()})}function k(){let i=b=S(),u=o.documentElement;return u.dataset.consent=i.status,u.dataset.consentRegion=i.region,u.toggleAttribute("data-consent-gpc",i.gpc),ce(i),C.forEach(f=>O(()=>f(i))),o.dispatchEvent(new CustomEvent(H,{detail:i})),i}async function q(i,u){if(!s)return;let f=JSON.stringify({policy:i.p,choices:i.c,action:i.a,gpc:t.gpc(),previousId:u}),d=await t.fetch(s.endpoint,{method:"POST",credentials:"same-origin",keepalive:!0,headers:{"content-type":"application/json"},body:f}).catch(()=>null),g=d?.ok?await d.json().catch(()=>null):null;l!==i||T()||typeof g?.id!="string"||!M.test(g.id)||(l={...i,r:g.id},delete l.q,N(),k())}async function le({action:i},{choices:u={}}={}){if(m)return k();let f=l?.r;l={v:1,p:e.policy,c:U({action:i,picked:u}),t:t.now(),a:i,...s?{q:1}:{}},N();let d=k(),g=q(l,f);return s&&ie({state:d})&&await ke(g,s.waitMs??1500),b}function ue(i){if(m&&(!i.supportsAnonymous||i.category!=="analytics"))return;let u={entry:i,generation:0,adapter:typeof i.grant=="function"?i:void 0};p.set(i.id,u),m||b.allowed[i.category]?j(u):x({doc:o,storage:i.storage}),O(()=>u.adapter?.onState?.({state:b,purge:x}))}function F(i){let u=new Set(i.map(f=>f.id));for(let[f,d]of p)u.has(f)||(p.delete(f),d.run&&L(d).then(g=>{g&&t.reload()}));for(let f of i)p.has(f.id)||ue(f)}function T(){let i=c();return!i&&!A||["t","a","r"].every(u=>i?.[u]===l?.[u])?!1:(l=i,k(),!0)}let de={contract:1,plugins:r,set:le,get:()=>b,allows:({consent:i})=>X({state:b,consent:i}),subscribe:({listener:i})=>(C.add(i),()=>{C.delete(i)}),open:()=>{o.dispatchEvent(new CustomEvent(D))},setOpen:({open:i})=>{o.documentElement.toggleAttribute("data-consent-open",i)}};return r.subscribe({kind:P,listener:F}),F(r.list({kind:P})),e.plugins?.forEach(i=>r.registerPlugin(i,{source:"page"})),k(),o.addEventListener("visibilitychange",()=>{o.visibilityState==="visible"&&T()}),o.defaultView?.addEventListener("pageshow",T),l?.q&&l.p===e.policy&&q(l),de}function _({win:e},t={}){return{doc:e.document,fetch:e.fetch.bind(e),now:Date.now,reload:()=>e.location.reload(),gpc:()=>e.navigator.globalPrivacyControl===!0||e.navigator.doNotTrack==="1",importModule:n=>import(n)}}function re({doc:e},t={}){try{return JSON.parse(e.getElementById(B)?.textContent??"")}catch{return null}}function we({win:e=window}={},{ports:t=_({win:e}),bindBanner:n}={}){if(e.jiniConsent)return e.jiniConsent;let o=e.document,r=re({doc:o});if(r)return se(e,r,{ports:t,bindBanner:n})}function se(e,t,{ports:n=_({win:e}),bindBanner:o}){let r=e.document,s=Re({config:t,ports:n},{evidence:t.evidence}),p=Array.isArray(e.jiniConsentQueue)?e.jiniConsentQueue:[];return e.jiniConsent=s,e.jiniConsentQueue={push:(...C)=>C.forEach(y=>s.plugins.registerPlugin(y,{source:"queue"}))},e.jiniConsentQueue.push(...p),oe({api:s,doc:r}),t.banner==="jini"&&o?.({api:s,doc:r}),r.dispatchEvent(new CustomEvent(J,{detail:s})),s}async function ae({win:e},t={}){if(e.jiniConsent)return e.jiniConsent;let n=re({doc:e.document});if(!n||n.banner==="off")return;if(!n.context)return we({win:e},t);let o=t.ports??_({win:e});try{let r=await o.fetch(n.context,{credentials:"same-origin",cache:"no-store"}).then(s=>s.ok?s.json():null);if(!Te(r))return;if(r.policy!==n.policy){Oe({win:e,policy:n.policy,reload:o.reload});return}return se(e,{...n,regionMode:r.regionMode},{...t,ports:o})}catch{return}}function Oe({win:e,policy:t,reload:n}){try{let o=`jini-consent-reload:${t}`;if(e.sessionStorage.getItem(o))return;e.sessionStorage.setItem(o,"1"),n()}catch{}}function Te(e){let t=e;return t?.enabled===!0&&typeof t.policy=="string"&&["auto","opt-in","opt-out"].includes(String(t.regionMode))}ae({win:window});})();
@@ -142,10 +142,17 @@ export interface StoragePrefixes {
142
142
  export interface Revoker {
143
143
  revoke?(): boolean | Promise<boolean>;
144
144
  }
145
+ /** The shape of the client's `purgeStorage`: removes the named cookie and localStorage prefixes from `doc`. */
146
+ export type PurgeStorage = (required: {
147
+ doc: Document;
148
+ storage: StoragePrefixes;
149
+ }, optional?: object) => void;
150
+ /** `purge` is the client runtime's own purge: a separately delivered adapter module cannot import it. */
145
151
  export interface GrantInput<C> {
146
152
  config: C;
147
153
  state: ConsentState;
148
154
  signal: AbortSignal;
155
+ purge: PurgeStorage;
149
156
  }
150
157
  /** Lives in the vendor's plugin. grant() returns null when it ran no vendor code (signal aborted first). */
151
158
  export interface ConsentAdapter<C = unknown> extends Contribution<typeof ADAPTER_KIND> {
@@ -158,6 +165,7 @@ export interface ConsentAdapter<C = unknown> extends Contribution<typeof ADAPTER
158
165
  /** Receives levels for cleanup even without a grant; must never start denied analytics. */
159
166
  onState?(required: {
160
167
  state: ConsentState;
168
+ purge: PurgeStorage;
161
169
  }, optional?: object): void;
162
170
  }
163
171
  /** Page-config form: `src` is imported on grant, or for cleanup when off and supportsAnonymous.
@@ -38,15 +38,20 @@ export function clamp({ flags, gpc }, _optional = {}) {
38
38
  * @example effective({ stored, policy: '2026-10-26', region: 'opt-in', gpc: false, nowMs: Date.now() }, { durable: true })
39
39
  * @complexity O(1). */
40
40
  export function effective({ stored, policy, region, gpc, nowMs }, { maxAgeMs = DEFAULT_MAX_AGE_MS, durable = false, anonymous = false } = {}) {
41
- // Banner-off never revives an old identity or consent grant, even in an opt-out region.
42
- // Policy mismatch, future (beyond skew) and expired choices are all stale.
43
- const live = !anonymous && stored && stored.p === policy && stored.t <= nowMs + SKEW_MS && nowMs - stored.t <= maxAgeMs ? stored : null;
41
+ const live = liveChoice({ stored, policy, nowMs }, { maxAgeMs, anonymous });
44
42
  const choices = clamp({ flags: anonymous ? DENIED : live?.c ?? flags(region === 'opt-out'), gpc });
45
43
  const base = { contract: 1, policy, region, gpc, choices, ...permissionFor({ choices, live, durable, anonymous, gpc }) };
46
44
  if (!live)
47
45
  return { ...base, status: 'pending', action: null, at: null, receipt: 'none' };
48
46
  return { ...base, status: 'set', action: live.a, at: live.t, receipt: receiptOf(live) };
49
47
  }
48
+ /** The stored choice that still counts, or null when it is stale or anonymous delivery ignores it.
49
+ * @complexity O(1). */
50
+ function liveChoice({ stored, policy, nowMs }, { maxAgeMs = DEFAULT_MAX_AGE_MS, anonymous = false } = {}) {
51
+ // Banner-off never revives an old identity or consent grant, even in an opt-out region.
52
+ // Policy mismatch, future (beyond skew) and expired choices are all stale.
53
+ return !anonymous && stored && stored.p === policy && stored.t <= nowMs + SKEW_MS && nowMs - stored.t <= maxAgeMs ? stored : null;
54
+ }
50
55
  /** Runtime permissions differ from choices for anonymous delivery and unconfirmed durable grants.
51
56
  * @complexity O(1). */
52
57
  function permissionFor({ choices, live, durable, anonymous, gpc }, _optional = {}) {
@@ -1 +1 @@
1
- "use strict";(()=>{var x="jini:consent-ready",S="jini:consent-open",v="jini-consent-config",g=["functional","analytics","marketing"],m=["necessary",...g];var u="consent-bridge";function f({state:e,consent:t=[]},n={}){return t.every(o=>m.includes(o)&&e.allowed[o]===!0)}function O(e){if(!/^(?:https?:\/\/|\/(?!\/)|\.\.?\/)/.test(e))return!1;try{return["http:","https:"].includes(new URL(e,"https://declared.invalid").protocol)}catch{return!1}}function w(e){if(!e||typeof e!="object")return!1;let{src:t,consent:n}=e;return typeof t!="string"||!t.trim()||/[\s\\]/.test(t)||!O(t)?!1:n===void 0||Array.isArray(n)&&n.every(o=>m.includes(o))}function E({scripts:e},t={}){if(e===void 0)return{scripts:[],problems:[]};if(!Array.isArray(e))return{scripts:[],problems:["scripts must be an array"]};let n=[],o=[];return e.forEach((a,i)=>{w(a)?n.push({src:a.src,...a.consent&&{consent:[...a.consent]}}):o.push(`scripts[${i}] needs an HTTP(S) or relative src and known consent categories`)}),{scripts:n,problems:o}}function N(e){let t={};for(let n of g){let o=e.querySelector(`input[name="${n}"]`);o&&(t[n]=o.checked)}return t}function y(e,t){for(let n of g){let o=e.querySelector(`input[name="${n}"]`);o&&(o.checked=t.choices[n],o.disabled=t.gpc&&n!=="functional")}}var C=e=>g.some(t=>e.choices[t]&&!e.allowed[t]);function h({api:e,doc:t}){let n=t.getElementById("jini-consent");if(!n)return;let o=n.querySelector("[data-consent-error]"),a=r=>{n.hidden=!r,e.setOpen({open:r})},i=r=>{o&&(o.hidden=!C(r)),C(r)||a(!1)};n.addEventListener("click",r=>{let s=r.target.closest?.("[data-consent-action]")?.dataset.consentAction;s&&(r.preventDefault(),e.set({action:s},{choices:N(n)}).then(i))}),n.addEventListener("keydown",r=>{r.key==="Escape"&&e.get().status==="set"&&a(!1)}),t.addEventListener(S,()=>{y(n,e.get()),a(!0),n.querySelector("button")?.focus()}),e.subscribe({listener:r=>{y(n,r),o&&!o.hidden&&!C(r)&&i(r)}}),y(n,e.get()),a(e.get().status==="pending")}function A({doc:e,reload:t},n={}){let o=[...e.querySelectorAll("iframe[data-src][data-jini-consent]")].map(i=>({node:i,consent:P(i),started:!1})),a=!1;return i=>{if(a)return;let r=o.filter(s=>s.started&&!f({state:i,consent:s.consent}));if(r.length){a=!0,r.forEach(s=>s.node.removeAttribute("src")),t();return}o.forEach(s=>{s.started||!f({state:i,consent:s.consent})||(s.started=!0,s.node.setAttribute("src",s.node.dataset.src))})}}function P(e){try{let t=JSON.parse(e.dataset.jiniConsent);if(Array.isArray(t))return t}catch{}return["invalid"]}var j={kind:u,accept:({contribution:e})=>typeof e.mount=="function"||typeof e.src=="string"?e:"mount() or module src needed"};function L(e){e.disposed=!0;try{e.dispose?.()}catch{}}function R({api:e,doc:t},n={}){let o=new Map;function a(i){for(let[r,s]of o)i.some(d=>d.id===r)||(L(s),o.delete(r));for(let r of i){if(o.has(r.id))continue;let s={disposed:!1,dispose:void 0};o.set(r.id,s);let d=c=>{if(!s.disposed)try{let l=c.mount?.({api:e,doc:t});typeof l=="function"&&(s.dispose=l)}catch{}};r.mount?d(r):import(r.src).then(c=>d(c.default)).catch(()=>{})}}e.plugins.defineSlot({slot:j}),e.plugins.subscribe({kind:u,listener:i=>a(i)}),a(e.plugins.list({kind:u}))}function D({doc:e,scripts:t,reload:n},o={}){let a=E({scripts:t}).scripts.map(c=>({script:c,started:!1,node:null})),i=null,r,s=!1;function d(){if(i||s)return;let c=a.find(b=>!b.started&&f({state:r,consent:b.script.consent}));if(!c)return;c.started=!0;let l=e.createElement("script");c.node=i=l,l.async=!1,l.src=c.script.src;let p=()=>{i===l&&(i=null),d()};l.onload=p,l.onerror=p,e.head.append(l)}return c=>{r=c;let l=a.filter(p=>p.started&&!f({state:c,consent:p.script.consent}));l.length&&!s&&(s=!0,l.forEach(p=>p.node?.remove()),n()),d()}}var k=Symbol.for("jini-consent:features");function I({api:e,doc:t,config:n,reload:o},{bindBanner:a}={}){if(Object.prototype.hasOwnProperty.call(e,k))return;Object.defineProperty(e,k,{value:!0});let i=M({doc:t,config:n,reload:o});e.subscribe({listener:i}),i(e.get()),R({api:e,doc:t}),n.banner==="jini"&&a&&e.plugins.registerPlugin({id:"jini-banner",kind:u,mount:a})}function M({doc:e,config:t,reload:n}){let o=!1,a=!1,i=()=>{o=!0},r=D({doc:e,scripts:t.scripts??[],reload:i}),s=A({doc:e,reload:i});return d=>{s(d),r(d),!(!o||a)&&(a=!0,n())}}function T(){let e=window.jiniConsent;if(e)try{let t=JSON.parse(document.getElementById(v)?.textContent??"");I({api:e,doc:document,config:t,reload:()=>location.reload()},{bindBanner:h})}catch{}}document.addEventListener(x,T);T();})();
1
+ "use strict";(()=>{var x="jini:consent-ready",S="jini:consent-open",v="jini-consent-config",g=["functional","analytics","marketing"],m=["necessary",...g];var u="consent-bridge";function f({state:e,consent:n=[]},t={}){return n.every(o=>m.includes(o)&&e.allowed[o]===!0)}function O(e){if(!/^(?:https?:\/\/|\/(?!\/)|\.\.?\/)/.test(e))return!1;try{return["http:","https:"].includes(new URL(e,"https://declared.invalid").protocol)}catch{return!1}}function w(e){if(!e||typeof e!="object")return!1;let{src:n,consent:t}=e;return typeof n!="string"||!n.trim()||/[\s\\]/.test(n)||!O(n)?!1:t===void 0||Array.isArray(t)&&t.every(o=>m.includes(o))}function E({scripts:e},n={}){if(e===void 0)return{scripts:[],problems:[]};if(!Array.isArray(e))return{scripts:[],problems:["scripts must be an array"]};let t=[],o=[];return e.forEach((a,i)=>{w(a)?t.push({src:a.src,...a.consent&&{consent:[...a.consent]}}):o.push(`scripts[${i}] needs an HTTP(S) or relative src and known consent categories`)}),{scripts:t,problems:o}}function P(e){let n={};for(let t of g){let o=e.querySelector(`input[name="${t}"]`);o&&(n[t]=o.checked)}return n}function y(e,n){for(let t of g){let o=e.querySelector(`input[name="${t}"]`);o&&(o.checked=n.choices[t],o.disabled=n.gpc&&t!=="functional")}}var C=({state:e},n={})=>g.some(t=>e.choices[t]&&!e.allowed[t]);function h({api:e,doc:n}){let t=n.getElementById("jini-consent");if(!t)return;let o=t.querySelector("[data-consent-error]"),a=r=>{t.hidden=!r,e.setOpen({open:r})},i=r=>{o&&(o.hidden=!C({state:r})),C({state:r})||a(!1)};t.addEventListener("click",r=>{let s=r.target.closest?.("[data-consent-action]")?.dataset.consentAction;s&&(r.preventDefault(),e.set({action:s},{choices:P(t)}).then(i))}),t.addEventListener("keydown",r=>{r.key==="Escape"&&e.get().status==="set"&&a(!1)}),n.addEventListener(S,()=>{y(t,e.get()),a(!0),t.querySelector("button")?.focus()}),e.subscribe({listener:r=>{y(t,r),o&&!o.hidden&&!C({state:r})&&i(r)}}),y(t,e.get()),a(e.get().status==="pending")}function A({doc:e,reload:n},t={}){let o=[...e.querySelectorAll("iframe[data-src][data-jini-consent]")].map(i=>({node:i,consent:j(i),started:!1})),a=!1;return i=>{if(a)return;let r=o.filter(s=>s.started&&!f({state:i,consent:s.consent}));if(r.length){a=!0,r.forEach(s=>s.node.removeAttribute("src")),n();return}o.forEach(s=>{s.started||!f({state:i,consent:s.consent})||(s.started=!0,s.node.setAttribute("src",s.node.dataset.src))})}}function j(e){try{let n=JSON.parse(e.dataset.jiniConsent);if(Array.isArray(n))return n}catch{}return["invalid"]}var N={kind:u,accept:({contribution:e})=>typeof e.mount=="function"||typeof e.src=="string"?e:"mount() or module src needed"};function L(e){e.disposed=!0;try{e.dispose?.()}catch{}}function R({api:e,doc:n},t={}){let o=new Map;function a(i){for(let[r,s]of o)i.some(d=>d.id===r)||(L(s),o.delete(r));for(let r of i){if(o.has(r.id))continue;let s={disposed:!1,dispose:void 0};o.set(r.id,s);let d=c=>{if(!s.disposed)try{let l=c.mount?.({api:e,doc:n});typeof l=="function"&&(s.dispose=l)}catch{}};r.mount?d(r):import(r.src).then(c=>d(c.default)).catch(()=>{})}}e.plugins.defineSlot({slot:N}),e.plugins.subscribe({kind:u,listener:i=>a(i)}),a(e.plugins.list({kind:u}))}function D({doc:e,scripts:n,reload:t},o={}){let a=E({scripts:n}).scripts.map(c=>({script:c,started:!1,node:null})),i=null,r,s=!1;function d(){if(i||s)return;let c=a.find(b=>!b.started&&f({state:r,consent:b.script.consent}));if(!c)return;c.started=!0;let l=e.createElement("script");c.node=i=l,l.async=!1,l.src=c.script.src;let p=()=>{i===l&&(i=null),d()};l.onload=p,l.onerror=p,e.head.append(l)}return c=>{r=c;let l=a.filter(p=>p.started&&!f({state:c,consent:p.script.consent}));l.length&&!s&&(s=!0,l.forEach(p=>p.node?.remove()),t()),d()}}var k=Symbol.for("jini-consent:features");function I({api:e,doc:n,config:t,reload:o},{bindBanner:a}={}){if(Object.prototype.hasOwnProperty.call(e,k))return;Object.defineProperty(e,k,{value:!0});let i=M({doc:n,config:t,reload:o});e.subscribe({listener:i}),i(e.get()),R({api:e,doc:n}),t.banner==="jini"&&a&&e.plugins.registerPlugin({id:"jini-banner",kind:u,mount:a})}function M({doc:e,config:n,reload:t}){let o=!1,a=!1,i=()=>{o=!0},r=D({doc:e,scripts:n.scripts??[],reload:i}),s=A({doc:e,reload:i});return d=>{s(d),r(d),!(!o||a)&&(a=!0,t())}}function T(){let e=window.jiniConsent;if(e)try{let n=JSON.parse(document.getElementById(v)?.textContent??"");I({api:e,doc:document,config:n,reload:()=>location.reload()},{bindBanner:h})}catch{}}document.addEventListener(x,T);T();})();
@@ -38,13 +38,14 @@ export type ConsentAtomicWriter = (required: {
38
38
  mode: number;
39
39
  refuseSymlink: boolean;
40
40
  }) => Promise<void>;
41
+ type ConsentFilesystem = Pick<typeof fs, 'link' | 'unlink' | 'open' | 'readdir' | 'stat'>;
41
42
  /** Publish a flushed staging file with an exclusive hard link, then flush the directory on non-Windows hosts.
42
43
  * Filesystem/link failures propagate. No reader ever sees a partially-written proof file.
43
44
  * @complexity Startup O(r log r) time/O(r) space; subsequent writes amortized O(1) plus bounded receipt I/O. */
44
45
  export declare function createNodeConsentFiles({ atomicWrite }: {
45
46
  atomicWrite: ConsentAtomicWriter;
46
47
  }, { filesystem, uniqueId, maximumRecords, retentionMs, nowMs, platform }?: {
47
- filesystem?: Pick<typeof fs, 'link' | 'unlink' | 'open' | 'readdir' | 'stat'>;
48
+ filesystem?: ConsentFilesystem;
48
49
  uniqueId?: () => string;
49
50
  maximumRecords?: number;
50
51
  retentionMs?: number;
@@ -64,4 +65,5 @@ export declare function createConsentFileRecords({ directory, files }: {
64
65
  export declare function consentRateLimitKey({ address }: {
65
66
  address: string;
66
67
  }, _options?: {}): string;
68
+ export {};
67
69
  //# sourceMappingURL=index.d.ts.map