@jini-ai/cookie-consent 0.6.15 → 0.6.16

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.
@@ -1,7 +1,6 @@
1
1
  /** @file DOM helpers for the browser client: cookies, storage purge, inert tags and the Jini banner binding.
2
2
  * The Jini banner is a client of the public API, exactly like an owner's own ("My own") banner. */
3
3
  import { OPEN_EVENT, OPTIONAL } from '../contract.js';
4
- const INERT = 'script[type="text/plain"][data-consent-category],iframe[data-consent-category][data-src]';
5
4
  const SKIP = ['type', 'data-src', 'data-type', 'data-consent-category'];
6
5
  // Not <html>: the client sets html[data-consent-open] while the banner shows, and every click's closest() would hit it.
7
6
  const OPENERS = ':not(html)[data-consent-open],a[href="#privacy-choices"]';
@@ -44,22 +43,26 @@ export function purge(doc, storage) {
44
43
  }
45
44
  catch { /* no storage: nothing to purge */ }
46
45
  }
47
- // MOVED-FROM: @jini-ai/cms consent/html/client.ts template release (ordered, each template consumed once).
46
+ // Resource templates are owned by the CMS gate; consume its output rather than re-encoding subtrees.
48
47
  // Follow-up (P4): delete the cms runtime once the consumer inserts this client.
49
48
  /** Allowed inert tags become live, in authored order (async=false). Unknown labels stay inert.
50
49
  * @complexity O(inert tags). */
51
50
  export function activateInert(doc, { allowed, ran }) {
52
- doc.querySelectorAll(INERT).forEach(node => {
53
- const category = node.dataset.consentCategory;
51
+ // One category guard handles legacy tags and CMS templates, including unlabelled resources.
52
+ doc.querySelectorAll('script[type="text/plain"],iframe[data-src],template[data-jini-consent-resource]').forEach(node => {
53
+ const content = node.content;
54
+ const category = (content ? node.dataset.category : node.dataset.consentCategory);
54
55
  if (!OPTIONAL.includes(category) || !allowed[category])
55
56
  return;
56
57
  ran.add(category);
57
58
  if (node.tagName === 'IFRAME') {
58
- node.setAttribute('src', node.dataset.src);
59
+ node.src = node.dataset.src;
59
60
  node.removeAttribute('data-src');
60
- return;
61
61
  }
62
- node.replaceWith(liveScript(doc, node));
62
+ else {
63
+ // Moving the fragment consumes the wrapper once and preserves the gate's markup and position.
64
+ node.replaceWith(content ?? liveScript(doc, node));
65
+ }
63
66
  });
64
67
  }
65
68
  function liveScript(doc, inert) {
@@ -121,7 +124,7 @@ export function bindBanner({ api, doc }) {
121
124
  show(false);
122
125
  };
123
126
  root.addEventListener('click', event => {
124
- const action = event.target.closest?.('[data-consent-action]')?.getAttribute('data-consent-action');
127
+ const action = event.target.closest?.('[data-consent-action]')?.dataset.consentAction;
125
128
  if (!action)
126
129
  return;
127
130
  event.preventDefault();
@@ -15,7 +15,7 @@ catch { /* a broken plugin or listener never blocks consent */ } };
15
15
  export function createCookieConsent({ config, ports }, options = {}) {
16
16
  const { doc } = ports;
17
17
  const plugins = options.plugins ?? createPluginRegistry({}, { slots: [ADAPTER_SLOT] });
18
- const durable = durableEvidence(options);
18
+ const durable = options.evidence?.mode === 'durable' ? options.evidence : null;
19
19
  const slots = new Map();
20
20
  const listeners = new Set();
21
21
  const ran = new Set(); // categories whose raw inert tags executed
@@ -104,7 +104,9 @@ export function createCookieConsent({ config, ports }, options = {}) {
104
104
  return;
105
105
  if (typeof out?.id !== 'string' || !RECEIPT_ID.test(out.id))
106
106
  return; // failed: q stays, retried at the next boot
107
- stored = { v: 1, p: choice.p, c: choice.c, t: choice.t, a: choice.a, r: out.id };
107
+ // Keep the choice intact, replacing its pending marker with the confirmed receipt.
108
+ stored = { ...choice, r: out.id };
109
+ delete stored.q;
108
110
  persist();
109
111
  apply(); // the receipt is what lets durable grants run
110
112
  }
@@ -152,7 +154,7 @@ export function createCookieConsent({ config, ports }, options = {}) {
152
154
  // A refused cookie write leaves only this tab's choice; absence cannot supersede it.
153
155
  if (!latest && !cookiePersisted)
154
156
  return false;
155
- if (sameStoredChoice({ latest, stored }))
157
+ if (latest?.t === stored?.t && latest?.a === stored?.a && latest?.r === stored?.r)
156
158
  return false;
157
159
  stored = latest;
158
160
  apply();
@@ -171,17 +173,11 @@ export function createCookieConsent({ config, ports }, options = {}) {
171
173
  apply();
172
174
  doc.addEventListener('visibilitychange', () => { if (doc.visibilityState === 'visible')
173
175
  adopt(); });
174
- doc.defaultView?.addEventListener('pageshow', () => adopt());
176
+ doc.defaultView?.addEventListener('pageshow', adopt);
175
177
  if (stored?.q && stored.p === config.policy)
176
178
  void confirm(stored); // durable retry of an earlier failed receipt
177
179
  return api;
178
180
  }
179
- function sameStoredChoice({ latest, stored }) {
180
- return latest?.t === stored?.t && latest?.a === stored?.a && latest?.r === stored?.r;
181
- }
182
- function durableEvidence({ evidence }, _optional = {}) {
183
- return evidence?.mode === 'durable' ? evidence : null;
184
- }
185
181
  export function browserPorts(win) {
186
182
  return {
187
183
  doc: win.document, fetch: win.fetch.bind(win), now: Date.now, reload: () => win.location.reload(),
@@ -206,15 +202,15 @@ export function boot(win = window, { ports = browserPorts(win), bindBanner } = {
206
202
  const page = readPage(doc);
207
203
  if (!page)
208
204
  return undefined;
209
- const { evidence, ...config } = page;
210
- const api = createCookieConsent({ config, ports }, { evidence });
205
+ // The parsed page already satisfies ClientConfig; avoid copying it just to omit evidence.
206
+ const api = createCookieConsent({ config: page, ports }, { evidence: page.evidence });
211
207
  // Before boot the queue is a plain array; an already-replaced queue object has nothing left to drain.
212
208
  const queued = Array.isArray(win.jiniConsentQueue) ? win.jiniConsentQueue : [];
213
209
  win.jiniConsent = api;
214
210
  win.jiniConsentQueue = { push: (...items) => items.forEach(item => api.plugins.registerPlugin(item, { source: 'queue' })) };
215
211
  win.jiniConsentQueue.push(...queued);
216
212
  installOpeners({ api, doc });
217
- if (config.banner === 'jini')
213
+ if (page.banner === 'jini')
218
214
  bindBanner?.({ api, doc });
219
215
  doc.dispatchEvent(new CustomEvent(READY_EVENT, { detail: api }));
220
216
  return api;
@@ -1 +1 @@
1
- "use strict";(()=>{var R="jini_choices",B="jini_region",G="jini:consent",V="jini:consent-ready",O="jini:consent-open",$="jini-consent-config",v=["functional","analytics","marketing"],Te=["necessary",...v],W=["accept","reject","save","do-not-sell","withdraw"];var P="consent-adapter";var N=864e5,le=180*N,ue=6e4,D=/^[\w-]{16,128}$/,z=Object.freeze({necessary:!0,functional:!1,analytics:!1,marketing:!1});function Q({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 Y({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 de({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:f=le,durable:a=!1,anonymous:d=!1}={}){let m=pe({stored:e,policy:t,nowMs:r,maxAgeMs:f,anonymous:d}),g=de({flags:d?z:m?.c??A(n==="opt-out"),gpc:o}),S={contract:1,policy:t,region:n,gpc:o,choices:g,...fe({choices:g,live:m,durable:a,anonymous:d,gpc:o})};return m?{...S,status:"set",action:m.a,at:m.t,receipt:ge(m)}:{...S,status:"pending",action:null,at:null,receipt:"none"}}function pe({stored:e,policy:t,nowMs:n,maxAgeMs:o,anonymous:r}){return r||!e||e.p!==t?null:e.t<=n+ue&&n-e.t<=o?e:null}function fe({choices:e,live:t,durable:n,anonymous:o,gpc:r},f={}){let a=t&&n&&!t.r,d=o||a?z:e,m=d.analytics?"full":"none";return{allowed:d,analyticsLevel:o&&!r?"anonymous":m}}function ge(e){return e.r?"stored":e.q?"pending":"local"}function X({raw:e},t={}){if(!e||e.length>1024)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!ye(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"&&D.test(n.r)&&(o.r=n.r),n.q===1&&(o.q=1),o}function ye(e){return!e||e.v!==1||typeof e.p!="string"||!Number.isFinite(e.t)?!1:W.includes(e.a)&&Ce(e.c)}function Ce(e){let t=e;return!t||typeof t!="object"?!1:typeof t.functional=="boolean"&&typeof t.analytics=="boolean"&&typeof t.marketing=="boolean"}var me=/^[a-z0-9][a-z0-9._:-]{0,63}$/;function Z(e={},{slots:t=[],onProblem:n=()=>{}}={}){let o=new Map,r=[],f=new Set,a=new Set,d=s=>r.filter(c=>c.kind===s).sort((c,l)=>l.priority-c.priority).map(c=>c.value),m=s=>a.forEach(c=>{if(c.kind===s)try{c.fn(d(s))}catch{}});function g(s,c){let l=h=>(n({id:String(s.id),kind:s.kind,reason:h,...c.source?{source:c.source}:{}}),()=>{});if(!me.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(h=>h.kind===s.kind&&h.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),m(s.kind),()=>{let h=r.indexOf(b);h>=0&&(r.splice(h,1),m(s.kind))}}let S={defineSlot({slot:s}){if(!o.has(s.kind)){o.set(s.kind,s);for(let c of f)c.raw.kind===s.kind&&(f.delete(c),c.dispose=g(c.raw,c.options))}},registerPlugin(s,c={}){if(o.has(s.kind))return g(s,c);let l={raw:s,options:c,dispose:()=>{f.delete(l)}};return f.add(l),()=>l.dispose()},list:({kind:s})=>d(s),subscribe({kind:s,listener:c}){let l={kind:s,fn:c};return a.add(l),()=>{a.delete(l)}}};for(let s of t)S.defineSlot({slot:s});return S}var ee={kind:P,accept({contribution:e}){return v.includes(e.category)?typeof e.grant=="function"||typeof e.src=="string"?e:"grant() or src needed":"category must be functional, analytics or marketing"}};var be='script[type="text/plain"][data-consent-category],iframe[data-consent-category][data-src]',Se=["type","data-src","data-type","data-consent-category"],he=':not(html)[data-consent-open],a[href="#privacy-choices"]';function w(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 te(e,{name:t,value:n,maxAgeS:o},{domain:r}={}){let f=e.defaultView?.location.protocol==="https:"?"; Secure":"";e.cookie=`${t}=${encodeURIComponent(n)}; Path=/; Max-Age=${Math.floor(o)}; SameSite=Lax${f}`+(r?"; Domain="+r:"")}function ve(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))&&ve(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 ne(e,{allowed:t,ran:n}){e.querySelectorAll(be).forEach(o=>{let r=o.dataset.consentCategory;if(!(!v.includes(r)||!t[r])){if(n.add(r),o.tagName==="IFRAME"){o.setAttribute("src",o.dataset.src),o.removeAttribute("data-src");return}o.replaceWith(xe(e,o))}})}function xe(e,t){let n=e.createElement("script");for(let{name:o,value:r}of t.attributes)Se.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 L({api:e,doc:t}){t.addEventListener("click",n=>{n.target.closest?.(he)&&(n.preventDefault(),e.open())})}function Ae(e){let t={};for(let n of v){let o=e.querySelector(`input[name="${n}"]`);o&&(t[n]=o.checked)}return t}function _(e,t){for(let n of v){let o=e.querySelector(`input[name="${n}"]`);o&&(o.checked=t.choices[n],o.disabled=t.gpc&&n!=="functional")}}var k=e=>v.some(t=>e.choices[t]&&!e.allowed[t]);function j({api:e,doc:t}){let n=t.getElementById("jini-consent");if(!n)return;let o=n.querySelector("[data-consent-error]"),r=a=>{n.hidden=!a,e.setOpen({open:a})},f=a=>{o&&(o.hidden=!k(a)),k(a)||r(!1)};n.addEventListener("click",a=>{let d=a.target.closest?.("[data-consent-action]")?.getAttribute("data-consent-action");d&&(a.preventDefault(),e.set({action:d},{choices:Ae(n)}).then(f))}),n.addEventListener("keydown",a=>{a.key==="Escape"&&e.get().status==="set"&&r(!1)}),t.addEventListener(O,()=>{_(n,e.get()),r(!0),n.querySelector("button")?.focus()}),e.subscribe({listener:a=>{_(n,a),o&&!o.hidden&&!k(a)&&f(a)}}),_(n,e.get()),r(e.get().status==="pending")}var Ee=(e,t)=>Promise.race([e,new Promise(n=>setTimeout(n,t))]),T=e=>{try{e()}catch{}};function Pe({config:e,ports:t},n={}){let{doc:o}=t,r=n.plugins??Z({},{slots:[ee]}),f=Re(n),a=new Map,d=new Set,m=new Set,g=e.banner==="off",S=(e.maxAgeDays??180)*N,s=Q({configured:e.regionMode,hint:g?null:w(o,B)}),c=()=>g?null:X({raw:w(o,R)}),l=c(),x=!0,b=h();function h(){return U({stored:l,policy:e.policy,region:s,gpc:t.gpc(),nowMs:t.now()},{maxAgeMs:S,durable:!!f,anonymous:g})}function q(){let i=JSON.stringify(l);te(o,{name:R,value:i,maxAgeS:S/1e3},{domain:e.cookieDomain}),x=w(o,R)===i}function F(i){i.generation++;let p=new AbortController,u=Promise.resolve(i.adapter??t.importModule(i.entry.src).then(C=>i.adapter=C.default)).then(C=>(T(()=>C.onState?.({state:b})),p.signal.aborted||g&&b.analyticsLevel==="none"?null:Promise.resolve().then(()=>C.grant({config:i.entry.config??C.config,state:b,signal:p.signal})).then((ce={})=>ce,()=>({}))),()=>null);i.run={ctl:p,result:u}}async function K(i){let p=i.run,y=i.generation;i.run=void 0,p.ctl.abort();let u=await p.result;if(!u)return!1;let C=await Promise.resolve().then(()=>u.revoke?.()).catch(()=>!1);return!g&&i.generation===y&&M(o,i.adapter?.storage??i.entry.storage),!C}function ie(i){let p=[];for(let u of a.values()){let C=g?i.analyticsLevel==="anonymous":i.allowed[u.entry.category];C&&!u.run&&F(u),!C&&u.run&&p.push(K(u)),T(()=>u.adapter?.onState?.({state:i}))}g||ne(o,{allowed:i.allowed,ran:m});let y=v.some(u=>m.has(u)&&!i.allowed[u]);Promise.all(p).then(u=>{(y||u.includes(!0))&&t.reload()})}function E(){let i=b=h(),p=o.documentElement;return p.dataset.consent=i.status,p.dataset.consentRegion=i.region,p.toggleAttribute("data-consent-gpc",i.gpc),ie(i),d.forEach(y=>T(()=>y(i))),o.dispatchEvent(new CustomEvent(G,{detail:i})),i}async function H(i,p){if(!f)return;let y=JSON.stringify({policy:i.p,choices:i.c,action:i.a,gpc:t.gpc(),previousId:p}),u=await t.fetch(f.endpoint,{method:"POST",credentials:"same-origin",keepalive:!0,headers:{"content-type":"application/json"},body:y}).catch(()=>null),C=u?.ok?await u.json().catch(()=>null):null;l!==i||I()||typeof C?.id!="string"||!D.test(C.id)||(l={v:1,p:i.p,c:i.c,t:i.t,a:i.a,r:C.id},q(),E())}async function re({action:i},{choices:p={}}={}){if(g)return E();let y=l?.r;l={v:1,p:e.policy,c:Y({action:i,picked:p}),t:t.now(),a:i,...f?{q:1}:{}},q();let u=E(),C=H(l,y);return f&&k(u)&&await Ee(C,f.waitMs??1500),b}function se(i){if(g&&(!i.supportsAnonymous||i.category!=="analytics"))return;let p={entry:i,generation:0,adapter:typeof i.grant=="function"?i:void 0};a.set(i.id,p),g||b.allowed[i.category]?F(p):M(o,i.storage),T(()=>p.adapter?.onState?.({state:b}))}function J(i){let p=new Set(i.map(y=>y.id));for(let[y,u]of a)p.has(y)||(a.delete(y),u.run&&K(u).then(C=>{C&&t.reload()}));for(let y of i)a.has(y.id)||se(y)}function I(){let i=c();return!i&&!x||ke({latest:i,stored:l})?!1:(l=i,E(),!0)}let ae={contract:1,plugins:r,set:re,get:()=>b,subscribe:({listener:i})=>(d.add(i),()=>{d.delete(i)}),open:()=>{o.dispatchEvent(new CustomEvent(O))},setOpen:({open:i})=>{o.documentElement.toggleAttribute("data-consent-open",i)}};return r.subscribe({kind:P,listener:J}),J(r.list({kind:P})),e.plugins?.forEach(i=>r.registerPlugin(i,{source:"page"})),E(),o.addEventListener("visibilitychange",()=>{o.visibilityState==="visible"&&I()}),o.defaultView?.addEventListener("pageshow",()=>I()),l?.q&&l.p===e.policy&&H(l),ae}function ke({latest:e,stored:t}){return e?.t===t?.t&&e?.a===t?.a&&e?.r===t?.r}function Re({evidence:e},t={}){return e?.mode==="durable"?e:null}function Oe(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 we(e){try{return JSON.parse(e.getElementById($)?.textContent??"")}catch{return null}}function oe(e=window,{ports:t=Oe(e),bindBanner:n}={}){if(e.jiniConsent)return e.jiniConsent;let o=e.document,r=we(o);if(!r)return;let{evidence:f,...a}=r,d=Pe({config:a,ports:t},{evidence:f}),m=Array.isArray(e.jiniConsentQueue)?e.jiniConsentQueue:[];return e.jiniConsent=d,e.jiniConsentQueue={push:(...g)=>g.forEach(S=>d.plugins.registerPlugin(S,{source:"queue"}))},e.jiniConsentQueue.push(...m),L({api:d,doc:o}),a.banner==="jini"&&n?.({api:d,doc:o}),o.dispatchEvent(new CustomEvent(V,{detail:d})),d}oe(window,{bindBanner:j});})();
1
+ "use strict";(()=>{var R="jini_choices",B="jini_region",G="jini:consent",V="jini:consent-ready",O="jini:consent-open",$="jini-consent-config",v=["functional","analytics","marketing"],ke=["necessary",...v],W=["accept","reject","save","do-not-sell","withdraw"];var P="consent-adapter";var N=864e5,le=180*N,ue=6e4,D=/^[\w-]{16,128}$/,z=Object.freeze({necessary:!0,functional:!1,analytics:!1,marketing:!1});function Q({configured:e,hint:n},t={}){return e!=="auto"?e:n==="us"?"opt-out":"opt-in"}var x=(e,n=e,t=n)=>({functional:e,analytics:n,marketing:t});function Y({action:e,picked:n={}},t={}){return e==="accept"?x(!0):e==="save"?x(n.functional===!0,n.analytics===!0,n.marketing===!0):e==="do-not-sell"?x(n.functional!==!1,!1):x(!1)}function de({flags:e,gpc:n},t={}){return{necessary:!0,functional:e.functional,analytics:e.analytics&&!n,marketing:e.marketing&&!n}}function U({stored:e,policy:n,region:t,gpc:o,nowMs:r},{maxAgeMs:a=le,durable:c=!1,anonymous:f=!1}={}){let m=!f&&e&&e.p===n&&e.t<=r+ue&&r-e.t<=a?e:null,C=de({flags:f?z:m?.c??x(t==="opt-out"),gpc:o}),h={contract:1,policy:n,region:t,gpc:o,choices:C,...pe({choices:C,live:m,durable:c,anonymous:f,gpc:o})};return m?{...h,status:"set",action:m.a,at:m.t,receipt:fe(m)}:{...h,status:"pending",action:null,at:null,receipt:"none"}}function pe({choices:e,live:n,durable:t,anonymous:o,gpc:r},a={}){let c=n&&t&&!n.r,f=o||c?z:e,m=f.analytics?"full":"none";return{allowed:f,analyticsLevel:o&&!r?"anonymous":m}}function fe(e){return e.r?"stored":e.q?"pending":"local"}function X({raw:e},n={}){if(!e||e.length>1024)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!ge(t))return null;let o={v:1,p:t.p,c:x(t.c.functional,t.c.analytics,t.c.marketing),t:t.t,a:t.a};return typeof t.r=="string"&&D.test(t.r)&&(o.r=t.r),t.q===1&&(o.q=1),o}function ge(e){return!e||e.v!==1||typeof e.p!="string"||!Number.isFinite(e.t)?!1:W.includes(e.a)&&ye(e.c)}function ye(e){let n=e;return!n||typeof n!="object"?!1:["functional","analytics","marketing"].every(t=>Object.hasOwn(n,t)&&typeof n[t]=="boolean")}var me=/^[a-z0-9][a-z0-9._:-]{0,63}$/;function Z(e={},{slots:n=[],onProblem:t=()=>{}}={}){let o=new Map,r=[],a=new Set,c=new Set,f=s=>r.filter(u=>u.kind===s).sort((u,l)=>l.priority-u.priority).map(u=>u.value),m=s=>c.forEach(u=>{if(u.kind===s)try{u.fn(f(s))}catch{}});function C(s,u){let l=S=>(t({id:String(s.id),kind:s.kind,reason:S,...u.source?{source:u.source}:{}}),()=>{});if(!me.test(String(s.id)))return l("short lowercase id");let E=o.get(s.kind).accept({contribution:s});if(typeof E=="string")return l(E);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:E,priority:u.priority??0};return r.push(b),m(s.kind),()=>{let S=r.indexOf(b);S>=0&&(r.splice(S,1),m(s.kind))}}let h={defineSlot({slot:s}){if(!o.has(s.kind)){o.set(s.kind,s);for(let u of a)u.raw.kind===s.kind&&(a.delete(u),u.dispose=C(u.raw,u.options))}},registerPlugin(s,u={}){if(o.has(s.kind))return C(s,u);let l={raw:s,options:u,dispose:()=>{a.delete(l)}};return a.add(l),()=>l.dispose()},list:({kind:s})=>f(s),subscribe({kind:s,listener:u}){let l={kind:s,fn:u};return c.add(l),()=>{c.delete(l)}}};for(let s of n)h.defineSlot({slot:s});return h}var ee={kind:P,accept({contribution:e}){return v.includes(e.category)?typeof e.grant=="function"||typeof e.src=="string"?e:"grant() or src needed":"category must be functional, analytics or marketing"}};var Ce=["type","data-src","data-type","data-consent-category"],be=':not(html)[data-consent-open],a[href="#privacy-choices"]';function T(e,n){let t=e.cookie.split(/;\s*/).find(o=>o.startsWith(n+"="));try{return t?decodeURIComponent(t.slice(n.length+1)):null}catch{return null}}function te(e,{name:n,value:t,maxAgeS:o},{domain:r}={}){let a=e.defaultView?.location.protocol==="https:"?"; Secure":"";e.cookie=`${n}=${encodeURIComponent(t)}; Path=/; Max-Age=${Math.floor(o)}; SameSite=Lax${a}`+(r?"; Domain="+r:"")}function Se(e,n){let t=(e.defaultView?.location.hostname??"").split("."),o=`${n}=; Path=/; Max-Age=0`;e.cookie=o;for(let r=0;r<t.length-1;r++)e.cookie=`${o}; Domain=.${t.slice(r).join(".")}`}function M(e,n){if(n){for(let t of e.cookie.split(/;\s*/)){let o=t.split("=")[0];n.cookies?.some(r=>o.startsWith(r))&&Se(e,o)}try{let t=e.defaultView.localStorage;for(let o of Object.keys(t))n.local?.some(r=>o.startsWith(r))&&t.removeItem(o)}catch{}}}function ne(e,{allowed:n,ran:t}){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;!v.includes(a)||!n[a]||(t.add(a),o.tagName==="IFRAME"?(o.src=o.dataset.src,o.removeAttribute("data-src")):o.replaceWith(r??ve(e,o)))})}function ve(e,n){let t=e.createElement("script");for(let{name:o,value:r}of n.attributes)Ce.includes(o)||t.setAttribute(o,r);return n.nonce&&(t.nonce=n.nonce),n.dataset.type&&(t.type=n.dataset.type),n.dataset.src?t.src=n.dataset.src:t.text=n.text,t.async=!1,t}function L({api:e,doc:n}){n.addEventListener("click",t=>{t.target.closest?.(be)&&(t.preventDefault(),e.open())})}function he(e){let n={};for(let t of v){let o=e.querySelector(`input[name="${t}"]`);o&&(n[t]=o.checked)}return n}function _(e,n){for(let t of v){let o=e.querySelector(`input[name="${t}"]`);o&&(o.checked=n.choices[t],o.disabled=n.gpc&&t!=="functional")}}var k=e=>v.some(n=>e.choices[n]&&!e.allowed[n]);function j({api:e,doc:n}){let t=n.getElementById("jini-consent");if(!t)return;let o=t.querySelector("[data-consent-error]"),r=c=>{t.hidden=!c,e.setOpen({open:c})},a=c=>{o&&(o.hidden=!k(c)),k(c)||r(!1)};t.addEventListener("click",c=>{let f=c.target.closest?.("[data-consent-action]")?.dataset.consentAction;f&&(c.preventDefault(),e.set({action:f},{choices:he(t)}).then(a))}),t.addEventListener("keydown",c=>{c.key==="Escape"&&e.get().status==="set"&&r(!1)}),n.addEventListener(O,()=>{_(t,e.get()),r(!0),t.querySelector("button")?.focus()}),e.subscribe({listener:c=>{_(t,c),o&&!o.hidden&&!k(c)&&a(c)}}),_(t,e.get()),r(e.get().status==="pending")}var Ee=(e,n)=>Promise.race([e,new Promise(t=>setTimeout(t,n))]),w=e=>{try{e()}catch{}};function xe({config:e,ports:n},t={}){let{doc:o}=n,r=t.plugins??Z({},{slots:[ee]}),a=t.evidence?.mode==="durable"?t.evidence:null,c=new Map,f=new Set,m=new Set,C=e.banner==="off",h=(e.maxAgeDays??180)*N,s=Q({configured:e.regionMode,hint:C?null:T(o,B)}),u=()=>C?null:X({raw:T(o,R)}),l=u(),E=!0,b=S();function S(){return U({stored:l,policy:e.policy,region:s,gpc:n.gpc(),nowMs:n.now()},{maxAgeMs:h,durable:!!a,anonymous:C})}function q(){let i=JSON.stringify(l);te(o,{name:R,value:i,maxAgeS:h/1e3},{domain:e.cookieDomain}),E=T(o,R)===i}function F(i){i.generation++;let p=new AbortController,d=Promise.resolve(i.adapter??n.importModule(i.entry.src).then(y=>i.adapter=y.default)).then(y=>(w(()=>y.onState?.({state:b})),p.signal.aborted||C&&b.analyticsLevel==="none"?null:Promise.resolve().then(()=>y.grant({config:i.entry.config??y.config,state:b,signal:p.signal})).then((ce={})=>ce,()=>({}))),()=>null);i.run={ctl:p,result:d}}async function K(i){let p=i.run,g=i.generation;i.run=void 0,p.ctl.abort();let d=await p.result;if(!d)return!1;let y=await Promise.resolve().then(()=>d.revoke?.()).catch(()=>!1);return!C&&i.generation===g&&M(o,i.adapter?.storage??i.entry.storage),!y}function ie(i){let p=[];for(let d of c.values()){let y=C?i.analyticsLevel==="anonymous":i.allowed[d.entry.category];y&&!d.run&&F(d),!y&&d.run&&p.push(K(d)),w(()=>d.adapter?.onState?.({state:i}))}C||ne(o,{allowed:i.allowed,ran:m});let g=v.some(d=>m.has(d)&&!i.allowed[d]);Promise.all(p).then(d=>{(g||d.includes(!0))&&n.reload()})}function A(){let i=b=S(),p=o.documentElement;return p.dataset.consent=i.status,p.dataset.consentRegion=i.region,p.toggleAttribute("data-consent-gpc",i.gpc),ie(i),f.forEach(g=>w(()=>g(i))),o.dispatchEvent(new CustomEvent(G,{detail:i})),i}async function H(i,p){if(!a)return;let g=JSON.stringify({policy:i.p,choices:i.c,action:i.a,gpc:n.gpc(),previousId:p}),d=await n.fetch(a.endpoint,{method:"POST",credentials:"same-origin",keepalive:!0,headers:{"content-type":"application/json"},body:g}).catch(()=>null),y=d?.ok?await d.json().catch(()=>null):null;l!==i||I()||typeof y?.id!="string"||!D.test(y.id)||(l={...i,r:y.id},delete l.q,q(),A())}async function re({action:i},{choices:p={}}={}){if(C)return A();let g=l?.r;l={v:1,p:e.policy,c:Y({action:i,picked:p}),t:n.now(),a:i,...a?{q:1}:{}},q();let d=A(),y=H(l,g);return a&&k(d)&&await Ee(y,a.waitMs??1500),b}function se(i){if(C&&(!i.supportsAnonymous||i.category!=="analytics"))return;let p={entry:i,generation:0,adapter:typeof i.grant=="function"?i:void 0};c.set(i.id,p),C||b.allowed[i.category]?F(p):M(o,i.storage),w(()=>p.adapter?.onState?.({state:b}))}function J(i){let p=new Set(i.map(g=>g.id));for(let[g,d]of c)p.has(g)||(c.delete(g),d.run&&K(d).then(y=>{y&&n.reload()}));for(let g of i)c.has(g.id)||se(g)}function I(){let i=u();return!i&&!E||i?.t===l?.t&&i?.a===l?.a&&i?.r===l?.r?!1:(l=i,A(),!0)}let ae={contract:1,plugins:r,set:re,get:()=>b,subscribe:({listener:i})=>(f.add(i),()=>{f.delete(i)}),open:()=>{o.dispatchEvent(new CustomEvent(O))},setOpen:({open:i})=>{o.documentElement.toggleAttribute("data-consent-open",i)}};return r.subscribe({kind:P,listener:J}),J(r.list({kind:P})),e.plugins?.forEach(i=>r.registerPlugin(i,{source:"page"})),A(),o.addEventListener("visibilitychange",()=>{o.visibilityState==="visible"&&I()}),o.defaultView?.addEventListener("pageshow",I),l?.q&&l.p===e.policy&&H(l),ae}function Ae(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:n=>import(n)}}function Pe(e){try{return JSON.parse(e.getElementById($)?.textContent??"")}catch{return null}}function oe(e=window,{ports:n=Ae(e),bindBanner:t}={}){if(e.jiniConsent)return e.jiniConsent;let o=e.document,r=Pe(o);if(!r)return;let a=xe({config:r,ports:n},{evidence:r.evidence}),c=Array.isArray(e.jiniConsentQueue)?e.jiniConsentQueue:[];return e.jiniConsent=a,e.jiniConsentQueue={push:(...f)=>f.forEach(m=>a.plugins.registerPlugin(m,{source:"queue"}))},e.jiniConsentQueue.push(...c),L({api:a,doc:o}),r.banner==="jini"&&t?.({api:a,doc:o}),o.dispatchEvent(new CustomEvent(V,{detail:a})),a}oe(window,{bindBanner:j});})();
@@ -39,19 +39,14 @@ export function clamp({ flags, gpc }, _optional = {}) {
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
41
  // Banner-off never revives an old identity or consent grant, even in an opt-out region.
42
- const live = current({ stored, policy, nowMs, maxAgeMs, anonymous });
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;
43
44
  const choices = clamp({ flags: anonymous ? DENIED : live?.c ?? flags(region === 'opt-out'), gpc });
44
45
  const base = { contract: 1, policy, region, gpc, choices, ...permissionFor({ choices, live, durable, anonymous, gpc }) };
45
46
  if (!live)
46
47
  return { ...base, status: 'pending', action: null, at: null, receipt: 'none' };
47
48
  return { ...base, status: 'set', action: live.a, at: live.t, receipt: receiptOf(live) };
48
49
  }
49
- /** Unparseable, future (beyond skew) and expired choices are all stale. @complexity O(1). */
50
- function current({ stored, policy, nowMs, maxAgeMs, anonymous }) {
51
- if (anonymous || !stored || stored.p !== policy)
52
- return null;
53
- return stored.t <= nowMs + SKEW_MS && nowMs - stored.t <= maxAgeMs ? stored : null;
54
- }
55
50
  /** Runtime permissions differ from choices for anonymous delivery and unconfirmed durable grants.
56
51
  * @complexity O(1). */
57
52
  function permissionFor({ choices, live, durable, anonymous, gpc }, _optional = {}) {
@@ -96,6 +91,6 @@ export function isFlags(c) {
96
91
  const f = c;
97
92
  if (!f || typeof f !== 'object')
98
93
  return false;
99
- return typeof f.functional === 'boolean' && typeof f.analytics === 'boolean' && typeof f.marketing === 'boolean';
94
+ return ['functional', 'analytics', 'marketing'].every(key => Object.hasOwn(f, key) && typeof f[key] === 'boolean');
100
95
  }
101
96
  //# sourceMappingURL=policy.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/cookie-consent",
3
- "version": "0.6.15",
3
+ "version": "0.6.16",
4
4
  "description": "Standalone, vendor-free cookie consent: a consent-state contract any banner can drive, a ~3 KB browser client, a pure-string banner renderer with owner CSS, web-standard receipts and open plugin slots.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -92,7 +92,8 @@
92
92
  "esbuild": "^0.28.1",
93
93
  "jsdom": "^25.0.1",
94
94
  "typescript": "^5.6.0",
95
- "vitest": "^2.1.0"
95
+ "vitest": "^2.1.0",
96
+ "@jini-ai/cms": "^0.6.16"
96
97
  },
97
98
  "scripts": {
98
99
  "build": "tsc -p tsconfig.json && node scripts/build-client.mjs",