@jini-ai/cookie-consent 0.0.0-stage → 0.6.15-rc.2

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.
@@ -0,0 +1,230 @@
1
+ /** @file Browser runtime (dist/client.min.js). It owns the cookie, the adapter lifecycle, inert tags and
2
+ * receipts. Denial is applied before any network; a durable grant runs only once its receipt exists; a
3
+ * response never sets a cookie, so a slow Accept can't overwrite a newer Reject. No polling, and no reload
4
+ * unless something already ran that cannot be stopped (a raw inert script, or an adapter that can't revoke). */
5
+ import { ADAPTER_KIND, CONFIG_ID, CONSENT_COOKIE, OPEN_EVENT, OPTIONAL, READY_EVENT, REGION_COOKIE, STATE_EVENT } from '../contract.js';
6
+ import { choicesFor, DAY_MS, effective, parseStored, RECEIPT_ID, regionFrom } from '../policy.js';
7
+ import { ADAPTER_SLOT, createPluginRegistry } from '../plugins.js';
8
+ import { activateInert, installOpeners, purge, readCookie, waiting, writeCookie } from './dom.js';
9
+ const within = (p, ms) => Promise.race([p, new Promise(r => setTimeout(r, ms))]);
10
+ const quiet = (fn) => { try {
11
+ fn();
12
+ }
13
+ catch { /* a broken plugin or listener never blocks consent */ } };
14
+ /** @example createCookieConsent({ config, ports: browserPorts(window) }, { evidence: { mode: 'local' } }) */
15
+ export function createCookieConsent({ config, ports }, options = {}) {
16
+ const { doc } = ports;
17
+ const plugins = options.plugins ?? createPluginRegistry({}, { slots: [ADAPTER_SLOT] });
18
+ const durable = durableEvidence(options);
19
+ const slots = new Map();
20
+ const listeners = new Set();
21
+ const ran = new Set(); // categories whose raw inert tags executed
22
+ const anonymous = config.banner === 'off';
23
+ const maxAgeMs = (config.maxAgeDays ?? 180) * DAY_MS;
24
+ const region = regionFrom({ configured: config.regionMode, hint: anonymous ? null : readCookie(doc, REGION_COOKIE) });
25
+ const fromCookie = () => anonymous ? null : parseStored({ raw: readCookie(doc, CONSENT_COOKIE) });
26
+ let stored = fromCookie();
27
+ let cookiePersisted = true;
28
+ let state = compute();
29
+ function compute() {
30
+ return effective({ stored, policy: config.policy, region, gpc: ports.gpc(), nowMs: ports.now() }, { maxAgeMs, durable: !!durable, anonymous });
31
+ }
32
+ function persist() {
33
+ const value = JSON.stringify(stored);
34
+ writeCookie(doc, { name: CONSENT_COOKIE, value, maxAgeS: maxAgeMs / 1000 }, { domain: config.cookieDomain });
35
+ cookiePersisted = readCookie(doc, CONSENT_COOKIE) === value;
36
+ }
37
+ /** Off-mode adapters load for identity cleanup even at none; only permitted levels grant.
38
+ * Abort is checked after the import and handed to grant(), so a withdrawal during either wait wins. */
39
+ function start(slot) {
40
+ slot.generation++;
41
+ const ctl = new AbortController();
42
+ const load = Promise.resolve(slot.adapter ?? ports.importModule(slot.entry.src).then(m => (slot.adapter = m.default)));
43
+ const result = load.then(adapter => {
44
+ quiet(() => adapter.onState?.({ state }));
45
+ if (ctl.signal.aborted || anonymous && state.analyticsLevel === 'none')
46
+ return null; // withdrawn first: nothing ran
47
+ return Promise.resolve().then(() => adapter.grant({ config: slot.entry.config ?? adapter.config, state, signal: ctl.signal }))
48
+ .then((r = {}) => r, () => ({})); // a grant that threw may have run code
49
+ }, () => null); // import failed: nothing ran
50
+ slot.run = { ctl, result };
51
+ }
52
+ /** Detached from set(): a hung import can never delay a withdrawal. Resolves true when a reload is needed.
53
+ * A newer grant owns its storage even if this revoke finishes after another withdrawal. */
54
+ async function stop(slot) {
55
+ const run = slot.run;
56
+ const generation = slot.generation;
57
+ slot.run = undefined;
58
+ run.ctl.abort();
59
+ const revoker = await run.result;
60
+ if (!revoker)
61
+ return false;
62
+ const clean = await Promise.resolve().then(() => revoker.revoke?.()).catch(() => false);
63
+ if (!anonymous && slot.generation === generation)
64
+ purge(doc, slot.adapter?.storage ?? slot.entry.storage);
65
+ return !clean;
66
+ }
67
+ function reconcile(next) {
68
+ const stops = [];
69
+ for (const slot of slots.values()) {
70
+ const allowed = anonymous ? next.analyticsLevel === 'anonymous' : next.allowed[slot.entry.category];
71
+ if (allowed) {
72
+ if (!slot.run)
73
+ start(slot);
74
+ }
75
+ else if (slot.run)
76
+ stops.push(stop(slot));
77
+ quiet(() => slot.adapter?.onState?.({ state: next }));
78
+ }
79
+ // Raw tags cannot promise anonymous behavior; only declared adapters can.
80
+ if (!anonymous)
81
+ activateInert(doc, { allowed: next.allowed, ran });
82
+ const rawRevoked = OPTIONAL.some(c => ran.has(c) && !next.allowed[c]);
83
+ void Promise.all(stops).then(dirty => { if (rawRevoked || dirty.includes(true))
84
+ ports.reload(); });
85
+ }
86
+ function apply() {
87
+ const next = (state = compute());
88
+ const html = doc.documentElement;
89
+ html.dataset.consent = next.status;
90
+ html.dataset.consentRegion = next.region;
91
+ html.toggleAttribute('data-consent-gpc', next.gpc);
92
+ reconcile(next); // stops start before any listener runs
93
+ listeners.forEach(fn => quiet(() => fn(next)));
94
+ doc.dispatchEvent(new CustomEvent(STATE_EVENT, { detail: next }));
95
+ return next;
96
+ }
97
+ async function confirm(choice, previousId) {
98
+ if (!durable)
99
+ return;
100
+ const body = JSON.stringify({ policy: choice.p, choices: choice.c, action: choice.a, gpc: ports.gpc(), previousId });
101
+ const res = await ports.fetch(durable.endpoint, { method: 'POST', credentials: 'same-origin', keepalive: true,
102
+ headers: { 'content-type': 'application/json' }, body }).catch(() => null);
103
+ const out = res?.ok ? (await res.json().catch(() => null)) : null;
104
+ // Superseded in this tab, or another tab wrote a newer choice (adopt it): the late receipt is ignored.
105
+ if (stored !== choice || adopt())
106
+ return;
107
+ if (typeof out?.id !== 'string' || !RECEIPT_ID.test(out.id))
108
+ return; // failed: q stays, retried at the next boot
109
+ stored = { v: 1, p: choice.p, c: choice.c, t: choice.t, a: choice.a, r: out.id };
110
+ persist();
111
+ apply(); // the receipt is what lets durable grants run
112
+ }
113
+ async function set({ action }, { choices: picked = {} } = {}) {
114
+ if (anonymous)
115
+ return apply();
116
+ const previousId = stored?.r;
117
+ stored = { v: 1, p: config.policy, c: choicesFor({ action, picked }), t: ports.now(), a: action, ...(durable ? { q: 1 } : {}) };
118
+ persist();
119
+ const now = apply(); // denial is live here, before any network
120
+ const sent = confirm(stored, previousId);
121
+ if (durable && waiting(now))
122
+ await within(sent, durable.waitMs ?? 1500);
123
+ return state;
124
+ }
125
+ function addSlot(entry) {
126
+ if (anonymous && (!entry.supportsAnonymous || entry.category !== 'analytics'))
127
+ return;
128
+ const slot = { entry, generation: 0, adapter: typeof entry.grant === 'function' ? entry : undefined };
129
+ slots.set(entry.id, slot);
130
+ if (anonymous || state.allowed[entry.category])
131
+ start(slot);
132
+ else
133
+ purge(doc, entry.storage); // leftovers of an expired or withdrawn choice
134
+ quiet(() => slot.adapter?.onState?.({ state })); // lazy adapters get state once loaded
135
+ }
136
+ function syncSlots(items) {
137
+ const ids = new Set(items.map(i => i.id));
138
+ for (const [id, slot] of slots) {
139
+ if (ids.has(id))
140
+ continue;
141
+ slots.delete(id);
142
+ if (slot.run)
143
+ void stop(slot).then(dirty => { if (dirty)
144
+ ports.reload(); });
145
+ }
146
+ for (const item of items)
147
+ if (!slots.has(item.id))
148
+ addSlot(item);
149
+ }
150
+ /** Another tab chose: adopt its cookie exactly as a page load would. Page-visible events only, no polling.
151
+ * Returns true when the cookie held a different choice. */
152
+ function adopt() {
153
+ const latest = fromCookie();
154
+ // A refused cookie write leaves only this tab's choice; absence cannot supersede it.
155
+ if (!latest && !cookiePersisted)
156
+ return false;
157
+ if (sameStoredChoice({ latest, stored }))
158
+ return false;
159
+ stored = latest;
160
+ apply();
161
+ return true;
162
+ }
163
+ const api = {
164
+ contract: 1, plugins, set,
165
+ get: () => state,
166
+ subscribe: ({ listener }) => { listeners.add(listener); return () => { listeners.delete(listener); }; },
167
+ open: () => { doc.dispatchEvent(new CustomEvent(OPEN_EVENT)); },
168
+ setOpen: ({ open }) => { doc.documentElement.toggleAttribute('data-consent-open', open); },
169
+ };
170
+ plugins.subscribe({ kind: ADAPTER_KIND, listener: syncSlots });
171
+ syncSlots(plugins.list({ kind: ADAPTER_KIND })); // registered before this client existed
172
+ config.plugins?.forEach(item => plugins.registerPlugin(item, { source: 'page' }));
173
+ apply();
174
+ doc.addEventListener('visibilitychange', () => { if (doc.visibilityState === 'visible')
175
+ adopt(); });
176
+ doc.defaultView?.addEventListener('pageshow', () => adopt());
177
+ if (stored?.q && stored.p === config.policy)
178
+ void confirm(stored); // durable retry of an earlier failed receipt
179
+ return api;
180
+ }
181
+ function sameStoredChoice({ latest, stored }) {
182
+ return latest?.t === stored?.t && latest?.a === stored?.a && latest?.r === stored?.r;
183
+ }
184
+ function durableEvidence({ evidence }, _optional = {}) {
185
+ return evidence?.mode === 'durable' ? evidence : null;
186
+ }
187
+ export function browserPorts(win) {
188
+ return {
189
+ doc: win.document, fetch: win.fetch.bind(win), now: Date.now, reload: () => win.location.reload(),
190
+ gpc: () => win.navigator.globalPrivacyControl === true || win.navigator.doNotTrack === '1',
191
+ importModule: src => import(/* @vite-ignore */ src),
192
+ };
193
+ }
194
+ function readPage(doc) {
195
+ try {
196
+ return JSON.parse(doc.getElementById(CONFIG_ID)?.textContent ?? '');
197
+ }
198
+ catch {
199
+ return null;
200
+ }
201
+ }
202
+ /** Reads #jini-consent-config, installs window.jiniConsent, drains and replaces the pre-boot queue.
203
+ * A missing or broken config installs nothing, so nothing optional can run (fail closed). */
204
+ export function boot(win = window, { ports = browserPorts(win), bindBanner } = {}) {
205
+ if (win.jiniConsent)
206
+ return win.jiniConsent;
207
+ const page = readPage(win.document);
208
+ if (!page)
209
+ return undefined;
210
+ const { evidence, ...config } = page;
211
+ const api = createCookieConsent({ config, ports }, { evidence });
212
+ // Before boot the queue is a plain array; an already-replaced queue object has nothing left to drain.
213
+ const queued = Array.isArray(win.jiniConsentQueue) ? win.jiniConsentQueue : [];
214
+ win.jiniConsent = api;
215
+ win.jiniConsentQueue = { push: (...items) => items.forEach(item => api.plugins.registerPlugin(item, { source: 'queue' })) };
216
+ win.jiniConsentQueue.push(...queued);
217
+ installOpeners({ api, doc: win.document });
218
+ if (config.banner === 'jini')
219
+ bindBanner?.({ api, doc: win.document });
220
+ win.document.dispatchEvent(new CustomEvent(READY_EVENT, { detail: api }));
221
+ return api;
222
+ }
223
+ /** Delete only the caller's storage prefixes; blocked localStorage is tolerated.
224
+ * @example purgeStorage({ doc: document, storage: { cookies: ['vendor_'], local: ['vendor_'] } })
225
+ * @complexity O(cookies + local keys), O(keys) temporary space; no new identity or network. */
226
+ export function purgeStorage({ doc, storage }, _optional = {}) {
227
+ purge(doc, storage);
228
+ }
229
+ export { bindBanner, installOpeners } from './dom.js';
230
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ "use strict";(()=>{var R="jini_choices",H="jini_region",J="jini:consent",$="jini:consent-ready",O="jini:consent-open",B="jini-consent-config",h=["functional","analytics","marketing"],we=["necessary",...h],G=["accept","reject","save","do-not-sell","withdraw"];var P="consent-adapter";var le='script[type="text/plain"][data-consent-category],iframe[data-consent-category][data-src]',ue=new Set(["type","data-src","data-type","data-consent-category"]),de=':not(html)[data-consent-open],a[href="#privacy-choices"]';function T(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 V(e,{name:t,value:n,maxAgeS:o},{domain:r}={}){let p=e.defaultView?.location.protocol==="https:"?"; Secure":"";e.cookie=`${t}=${encodeURIComponent(n)}; Path=/; Max-Age=${Math.floor(o)}; SameSite=Lax${p}${r?`; Domain=${r}`:""}`}function pe(e,t){let n=(e.defaultView?.location.hostname??"").split(".");e.cookie=`${t}=; Path=/; Max-Age=0`;for(let o=0;o<n.length-1;o++)e.cookie=`${t}=; Path=/; Max-Age=0; Domain=.${n.slice(o).join(".")}`}function D(e,t){if(t){for(let n of e.cookie.split(/;\s*/)){let o=n.split("=")[0];t.cookies?.some(r=>o.startsWith(r))&&pe(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 W(e,{allowed:t,ran:n}){e.querySelectorAll(le).forEach(o=>{let r=o.dataset.consentCategory;if(!(!h.includes(r)||!t[r])){if(n.add(r),o.tagName==="IFRAME"){o.setAttribute("src",o.dataset.src),o.removeAttribute("data-src");return}o.replaceWith(fe(e,o))}})}function fe(e,t){let n=e.createElement("script");for(let{name:o,value:r}of Array.from(t.attributes))ue.has(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 z({api:e,doc:t}){t.addEventListener("click",n=>{n.target.closest?.(de)&&(n.preventDefault(),e.open())})}function ge(e){let t={};for(let n of h){let o=e.querySelector(`input[name="${n}"]`);o&&(t[n]=o.checked)}return t}function N(e,t){for(let n of h){let o=e.querySelector(`input[name="${n}"]`);o&&(o.checked=t.choices[n],o.disabled=t.gpc&&n!=="functional")}}var k=e=>h.some(t=>e.choices[t]&&!e.allowed[t]);function Q({api:e,doc:t}){let n=t.getElementById("jini-consent");if(!n)return;let o=n.querySelector("[data-consent-error]"),r=s=>{n.hidden=!s,e.setOpen({open:s})},p=s=>{o&&(o.hidden=!k(s)),k(s)||r(!1)};n.addEventListener("click",s=>{let m=s.target.closest?.("[data-consent-action]")?.getAttribute("data-consent-action");m&&(s.preventDefault(),e.set({action:m},{choices:ge(n)}).then(p))}),n.addEventListener("keydown",s=>{s.key==="Escape"&&e.get().status==="set"&&r(!1)}),t.addEventListener(O,()=>{N(n,e.get()),r(!0),n.querySelector("button")?.focus()}),e.subscribe({listener:s=>{N(n,s),o&&!o.hidden&&!k(s)&&p(s)}}),N(n,e.get()),r(e.get().status==="pending")}var _=864e5,ye=180*_,me=6e4,M=/^[\w-]{16,128}$/,Y=Object.freeze({necessary:!0,functional:!1,analytics:!1,marketing:!1});function U({configured:e,hint:t},n={}){return e!=="auto"?e:t==="us"?"opt-out":"opt-in"}var x=(e,t=e,n=t)=>({functional:e,analytics:t,marketing:n});function X({action:e,picked:t={}},n={}){return e==="accept"?x(!0):e==="save"?x(t.functional===!0,t.analytics===!0,t.marketing===!0):e==="do-not-sell"?x(t.functional!==!1,!1):x(!1)}function Ce({flags:e,gpc:t},n={}){return{necessary:!0,functional:e.functional,analytics:e.analytics&&!t,marketing:e.marketing&&!t}}function Z({stored:e,policy:t,region:n,gpc:o,nowMs:r},{maxAgeMs:p=ye,durable:s=!1,anonymous:m=!1}={}){let C=be({stored:e,policy:t,nowMs:r,maxAgeMs:p,anonymous:m}),f=Ce({flags:m?Y:C?.c??x(n==="opt-out"),gpc:o}),v={contract:1,policy:t,region:n,gpc:o,choices:f,...Se({choices:f,live:C,durable:s,anonymous:m,gpc:o})};return C?{...v,status:"set",action:C.a,at:C.t,receipt:he(C)}:{...v,status:"pending",action:null,at:null,receipt:"none"}}function be({stored:e,policy:t,nowMs:n,maxAgeMs:o,anonymous:r}){return!r&&e&&e.p===t&&e.t<=n+me&&n-e.t<=o?e:null}function Se({choices:e,live:t,durable:n,anonymous:o,gpc:r},p={}){let s=o||t&&n&&!t.r?Y:e;return{allowed:s,analyticsLevel:o&&!r?"anonymous":s.analytics?"full":"none"}}function he(e){return e.r?"stored":e.q?"pending":"local"}function ee({raw:e},t={}){if(!e||e.length>1024)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!ve(n))return null;let o={v:1,p:n.p,c:x(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 ve(e){return!e||e.v!==1||typeof e.p!="string"||!Number.isFinite(e.t)?!1:G.includes(e.a)&&Ae(e.c)}function Ae(e){let t=e;return!!t&&typeof t=="object"&&typeof t.functional=="boolean"&&typeof t.analytics=="boolean"&&typeof t.marketing=="boolean"}var xe=/^[a-z0-9][a-z0-9._:-]{0,63}$/;function te(e={},{slots:t=[],onProblem:n=()=>{}}={}){let o=new Map,r=[],p=new Set,s=new Set,m=a=>r.filter(c=>c.kind===a).sort((c,l)=>l.priority-c.priority).map(c=>c.value),C=a=>s.forEach(c=>{if(c.kind===a)try{c.fn(m(a))}catch{}});function f(a,c){let l=S=>(n({id:String(a.id),kind:a.kind,reason:S,...c.source?{source:c.source}:{}}),()=>{});if(!xe.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),C(a.kind),()=>{let S=r.indexOf(b);S>=0&&(r.splice(S,1),C(a.kind))}}let v={defineSlot({slot:a}){if(!o.has(a.kind)){o.set(a.kind,a);for(let c of p)c.raw.kind===a.kind&&(p.delete(c),c.dispose=f(c.raw,c.options))}},registerPlugin(a,c={}){if(o.has(a.kind))return f(a,c);let l={raw:a,options:c,dispose:()=>{p.delete(l)}};return p.add(l),()=>l.dispose()},list:({kind:a})=>m(a),subscribe({kind:a,listener:c}){let l={kind:a,fn:c};return s.add(l),()=>{s.delete(l)}}};for(let a of t)v.defineSlot({slot:a});return v}var ne={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 Ee=(e,t)=>Promise.race([e,new Promise(n=>setTimeout(n,t))]),w=e=>{try{e()}catch{}};function Pe({config:e,ports:t},n={}){let{doc:o}=t,r=n.plugins??te({},{slots:[ne]}),p=Re(n),s=new Map,m=new Set,C=new Set,f=e.banner==="off",v=(e.maxAgeDays??180)*_,a=U({configured:e.regionMode,hint:f?null:T(o,H)}),c=()=>f?null:ee({raw:T(o,R)}),l=c(),A=!0,b=S();function S(){return Z({stored:l,policy:e.policy,region:a,gpc:t.gpc(),nowMs:t.now()},{maxAgeMs:v,durable:!!p,anonymous:f})}function L(){let i=JSON.stringify(l);V(o,{name:R,value:i,maxAgeS:v/1e3},{domain:e.cookieDomain}),A=T(o,R)===i}function j(i){i.generation++;let d=new AbortController,u=Promise.resolve(i.adapter??t.importModule(i.entry.src).then(y=>i.adapter=y.default)).then(y=>(w(()=>y.onState?.({state:b})),d.signal.aborted||f&&b.analyticsLevel==="none"?null:Promise.resolve().then(()=>y.grant({config:i.entry.config??y.config,state:b,signal:d.signal})).then((ce={})=>ce,()=>({}))),()=>null);i.run={ctl:d,result:u}}async function q(i){let d=i.run,g=i.generation;i.run=void 0,d.ctl.abort();let u=await d.result;if(!u)return!1;let y=await Promise.resolve().then(()=>u.revoke?.()).catch(()=>!1);return!f&&i.generation===g&&D(o,i.adapter?.storage??i.entry.storage),!y}function ie(i){let d=[];for(let u of s.values())(f?i.analyticsLevel==="anonymous":i.allowed[u.entry.category])?u.run||j(u):u.run&&d.push(q(u)),w(()=>u.adapter?.onState?.({state:i}));f||W(o,{allowed:i.allowed,ran:C});let g=h.some(u=>C.has(u)&&!i.allowed[u]);Promise.all(d).then(u=>{(g||u.includes(!0))&&t.reload()})}function E(){let i=b=S(),d=o.documentElement;return d.dataset.consent=i.status,d.dataset.consentRegion=i.region,d.toggleAttribute("data-consent-gpc",i.gpc),ie(i),m.forEach(g=>w(()=>g(i))),o.dispatchEvent(new CustomEvent(J,{detail:i})),i}async function F(i,d){if(!p)return;let g=JSON.stringify({policy:i.p,choices:i.c,action:i.a,gpc:t.gpc(),previousId:d}),u=await t.fetch(p.endpoint,{method:"POST",credentials:"same-origin",keepalive:!0,headers:{"content-type":"application/json"},body:g}).catch(()=>null),y=u?.ok?await u.json().catch(()=>null):null;l!==i||I()||typeof y?.id!="string"||!M.test(y.id)||(l={v:1,p:i.p,c:i.c,t:i.t,a:i.a,r:y.id},L(),E())}async function re({action:i},{choices:d={}}={}){if(f)return E();let g=l?.r;l={v:1,p:e.policy,c:X({action:i,picked:d}),t:t.now(),a:i,...p?{q:1}:{}},L();let u=E(),y=F(l,g);return p&&k(u)&&await Ee(y,p.waitMs??1500),b}function se(i){if(f&&(!i.supportsAnonymous||i.category!=="analytics"))return;let d={entry:i,generation:0,adapter:typeof i.grant=="function"?i:void 0};s.set(i.id,d),f||b.allowed[i.category]?j(d):D(o,i.storage),w(()=>d.adapter?.onState?.({state:b}))}function K(i){let d=new Set(i.map(g=>g.id));for(let[g,u]of s)d.has(g)||(s.delete(g),u.run&&q(u).then(y=>{y&&t.reload()}));for(let g of i)s.has(g.id)||se(g)}function I(){let i=c();return!i&&!A||ke({latest:i,stored:l})?!1:(l=i,E(),!0)}let ae={contract:1,plugins:r,set:re,get:()=>b,subscribe:({listener:i})=>(m.add(i),()=>{m.delete(i)}),open:()=>{o.dispatchEvent(new CustomEvent(O))},setOpen:({open:i})=>{o.documentElement.toggleAttribute("data-consent-open",i)}};return r.subscribe({kind:P,listener:K}),K(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&&F(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 Te(e){try{return JSON.parse(e.getElementById(B)?.textContent??"")}catch{return null}}function oe(e=window,{ports:t=Oe(e),bindBanner:n}={}){if(e.jiniConsent)return e.jiniConsent;let o=Te(e.document);if(!o)return;let{evidence:r,...p}=o,s=Pe({config:p,ports:t},{evidence:r}),m=Array.isArray(e.jiniConsentQueue)?e.jiniConsentQueue:[];return e.jiniConsent=s,e.jiniConsentQueue={push:(...C)=>C.forEach(f=>s.plugins.registerPlugin(f,{source:"queue"}))},e.jiniConsentQueue.push(...m),z({api:s,doc:e.document}),p.banner==="jini"&&n?.({api:s,doc:e.document}),e.document.dispatchEvent(new CustomEvent($,{detail:s})),s}oe(window,{bindBanner:Q});})();
@@ -0,0 +1,206 @@
1
+ /** @file @jini-ai/cookie-consent contract: the only module a banner, plugin or host feature needs to import.
2
+ * Types and constants only. Every call that injects something takes (required, optional): the first
3
+ * argument is an object of required fields/ports, the second an object of optional ones. */
4
+ export declare const CONTRACT: 1;
5
+ /** Separate from the CMS engine's HttpOnly jini_consent: browsers cannot overwrite that cookie. */
6
+ export declare const CONSENT_COOKIE = "jini_choices";
7
+ /** 'us' or absent. Absent (unknown region) = strict, with Reject on the first layer. */
8
+ export declare const REGION_COOKIE = "jini_region";
9
+ /** Dispatched on `document` on every change; detail: ConsentState. */
10
+ export declare const STATE_EVENT = "jini:consent";
11
+ /** Dispatched on `document` once the client is installed; detail: JiniConsentApi. */
12
+ export declare const READY_EVENT = "jini:consent-ready";
13
+ /** Dispatched on `document` when anything asks for the preferences UI (a footer link, the reopen button). */
14
+ export declare const OPEN_EVENT = "jini:consent-open";
15
+ /** Id of the JSON <script> that carries the PageConfig. */
16
+ export declare const CONFIG_ID = "jini-consent-config";
17
+ export declare const OPTIONAL: readonly ["functional", "analytics", "marketing"];
18
+ export type Optional = typeof OPTIONAL[number];
19
+ export declare const CATEGORIES: readonly ["necessary", "functional", "analytics", "marketing"];
20
+ export type Category = typeof CATEGORIES[number];
21
+ export type Flags = Record<Optional, boolean>;
22
+ export type Choices = Readonly<{
23
+ necessary: true;
24
+ } & Flags>;
25
+ export declare const ACTIONS: readonly ["accept", "reject", "save", "do-not-sell", "withdraw"];
26
+ export type ConsentAction = typeof ACTIONS[number];
27
+ export type RegionMode = 'opt-in' | 'opt-out';
28
+ /** A resolver's definite answer. Resolvers return null for "unknown: ask the next one". */
29
+ export type RegionHint = 'us' | 'strict';
30
+ /** jini = the built-in banner; headless = "My own" banner; off = anonymous analytics only, no UI. */
31
+ export declare const BANNER_MODES: readonly ["jini", "headless", "off"];
32
+ export type BannerMode = typeof BANNER_MODES[number];
33
+ /** durable = a server stores receipts and grants wait for one; local = browser-only evidence (static
34
+ * export, Electron, file:), labelled as such and never presented as a server receipt. */
35
+ export type Evidence = {
36
+ mode: 'durable';
37
+ endpoint: string;
38
+ waitMs?: number;
39
+ } | {
40
+ mode: 'local';
41
+ };
42
+ /** 'stored' = server receipt; 'pending' = sent, unconfirmed; 'local' = browser-only, labelled as such. */
43
+ export type ReceiptStatus = 'none' | 'local' | 'pending' | 'stored';
44
+ /** Cookie wire format (JSON, URI-encoded). `c` is what the visitor chose; GPC is applied on read.
45
+ * v = format, p = policy version, t = choice time (ms), a = action, r = receipt id, q = receipt pending. */
46
+ export interface StoredChoice {
47
+ v: 1;
48
+ p: string;
49
+ c: Flags;
50
+ t: number;
51
+ a: ConsentAction;
52
+ r?: string;
53
+ q?: 1;
54
+ }
55
+ export interface ConsentState {
56
+ contract: 1;
57
+ policy: string;
58
+ status: 'pending' | 'set';
59
+ region: RegionMode;
60
+ /** Effective privacy opt-out: GPC or DNT. The historical field name is retained on receipts. */
61
+ gpc: boolean;
62
+ /** Analytics adapters/collectors must enforce this level, not just allowed.analytics. */
63
+ analyticsLevel: 'none' | 'anonymous' | 'full';
64
+ /** What the banner shows: the choice (or region default), GPC-clamped. */
65
+ choices: Choices;
66
+ /** Full category permissions; durable grants await their receipt. Never read `choices` as permission.
67
+ * Anonymous analytics keeps allowed.analytics false; adapters/collectors use analyticsLevel. */
68
+ allowed: Choices;
69
+ action: ConsentAction | null;
70
+ at: number | null;
71
+ receipt: ReceiptStatus;
72
+ }
73
+ export interface Contribution<K extends string = string> {
74
+ readonly id: string;
75
+ readonly kind: K;
76
+ }
77
+ export type RawContribution = Contribution & Record<string, unknown>;
78
+ export interface SlotKind<T extends Contribution = Contribution> {
79
+ readonly kind: T['kind'];
80
+ /** Trust boundary: the typed, normalized contribution, or a plain-language reason to refuse it. */
81
+ accept(required: {
82
+ contribution: RawContribution;
83
+ }, optional?: object): T | string;
84
+ }
85
+ export interface RegistrationOptions {
86
+ priority?: number;
87
+ source?: string;
88
+ }
89
+ export interface SlotProblem {
90
+ id: string;
91
+ kind: string;
92
+ reason: string;
93
+ source?: string;
94
+ }
95
+ export interface PluginRegistry {
96
+ defineSlot(required: {
97
+ slot: SlotKind;
98
+ }, optional?: object): void;
99
+ /** A contribution for a kind nobody has defined yet is parked until defineSlot arrives. */
100
+ registerPlugin(required: RawContribution, optional?: RegistrationOptions): () => void;
101
+ list<T extends Contribution>(required: {
102
+ kind: T['kind'];
103
+ }, optional?: object): readonly T[];
104
+ subscribe(required: {
105
+ kind: string;
106
+ listener: (items: readonly Contribution[]) => void;
107
+ }, optional?: object): () => void;
108
+ }
109
+ export declare const ADAPTER_KIND = "consent-adapter";
110
+ export interface StoragePrefixes {
111
+ cookies?: readonly string[];
112
+ local?: readonly string[];
113
+ }
114
+ /** revoke() true = fully stopped; false or missing = the page reloads to be clean. */
115
+ export interface Revoker {
116
+ revoke?(): boolean | Promise<boolean>;
117
+ }
118
+ export interface GrantInput<C> {
119
+ config: C;
120
+ state: ConsentState;
121
+ signal: AbortSignal;
122
+ }
123
+ /** Lives in the vendor's plugin. grant() returns null when it ran no vendor code (signal aborted first). */
124
+ export interface ConsentAdapter<C = unknown> extends Contribution<typeof ADAPTER_KIND> {
125
+ category: Optional;
126
+ /** Only adapters explicitly implementing the anonymous restrictions may run at that level. */
127
+ supportsAnonymous?: true;
128
+ config?: C;
129
+ storage?: StoragePrefixes;
130
+ grant(required: GrantInput<C>, optional?: object): Promise<Revoker | null> | Revoker | null;
131
+ /** Receives levels for cleanup even without a grant; must never start denied analytics. */
132
+ onState?(required: {
133
+ state: ConsentState;
134
+ }, optional?: object): void;
135
+ }
136
+ /** Page-config form: `src` is imported on grant, or for cleanup when off and supportsAnonymous.
137
+ * An adapter that must signal before any grant in other banner modes (a
138
+ * consent-mode default) registers a live adapter through window.jiniConsentQueue instead. */
139
+ export interface LazyAdapter extends Contribution<typeof ADAPTER_KIND> {
140
+ category: Optional;
141
+ src: string;
142
+ config?: unknown;
143
+ storage?: StoragePrefixes;
144
+ supportsAnonymous?: true;
145
+ }
146
+ export type AdapterContribution = ConsentAdapter | LazyAdapter;
147
+ export declare const REGION_KIND = "region-resolver";
148
+ export interface RegionRequest {
149
+ header(name: string): string | null;
150
+ ip: string | null;
151
+ }
152
+ export interface RegionResolver extends Contribution<typeof REGION_KIND> {
153
+ resolve(required: {
154
+ request: RegionRequest;
155
+ }, optional?: {
156
+ signal?: AbortSignal;
157
+ }): RegionHint | null | Promise<RegionHint | null>;
158
+ }
159
+ /** Data-only form for a plugin manifest; the region slot turns it into a RegionResolver. */
160
+ export interface HeaderRegion extends Contribution<typeof REGION_KIND> {
161
+ header: string;
162
+ usValues?: readonly string[];
163
+ }
164
+ export interface ClientConfig {
165
+ contract: 1;
166
+ policy: string;
167
+ regionMode: 'auto' | RegionMode;
168
+ banner: BannerMode;
169
+ /** LazyAdapter entries and any future browser kinds; unknown kinds wait for their slot. */
170
+ plugins?: readonly RawContribution[];
171
+ maxAgeDays?: number;
172
+ cookieDomain?: string;
173
+ }
174
+ /** What #jini-consent-config holds: the config plus the evidence mode the host chose. */
175
+ export type PageConfig = ClientConfig & {
176
+ evidence?: Evidence;
177
+ };
178
+ export interface JiniConsentApi {
179
+ readonly contract: 1;
180
+ readonly plugins: PluginRegistry;
181
+ get(): ConsentState;
182
+ subscribe(required: {
183
+ listener: (state: ConsentState) => void;
184
+ }, optional?: object): () => void;
185
+ /** Denial applies before any network; GPC clamps the result and nothing can lift it. */
186
+ set(required: {
187
+ action: ConsentAction;
188
+ }, optional?: {
189
+ choices?: Partial<Flags>;
190
+ }): Promise<ConsentState>;
191
+ /** Ask whichever banner is installed to show its preferences (dispatches OPEN_EVENT). */
192
+ open(): void;
193
+ /** A banner reports whether it is showing, so html[data-consent-open] stays truthful for CSS. */
194
+ setOpen(required: {
195
+ open: boolean;
196
+ }, optional?: object): void;
197
+ }
198
+ declare global {
199
+ interface Window {
200
+ jiniConsent?: JiniConsentApi;
201
+ jiniConsentQueue?: {
202
+ push(...items: RawContribution[]): unknown;
203
+ };
204
+ }
205
+ }
206
+ //# sourceMappingURL=contract.d.ts.map
@@ -0,0 +1,26 @@
1
+ /** @file @jini-ai/cookie-consent contract: the only module a banner, plugin or host feature needs to import.
2
+ * Types and constants only. Every call that injects something takes (required, optional): the first
3
+ * argument is an object of required fields/ports, the second an object of optional ones. */
4
+ export const CONTRACT = 1;
5
+ /** Separate from the CMS engine's HttpOnly jini_consent: browsers cannot overwrite that cookie. */
6
+ export const CONSENT_COOKIE = 'jini_choices';
7
+ /** 'us' or absent. Absent (unknown region) = strict, with Reject on the first layer. */
8
+ export const REGION_COOKIE = 'jini_region';
9
+ /** Dispatched on `document` on every change; detail: ConsentState. */
10
+ export const STATE_EVENT = 'jini:consent';
11
+ /** Dispatched on `document` once the client is installed; detail: JiniConsentApi. */
12
+ export const READY_EVENT = 'jini:consent-ready';
13
+ /** Dispatched on `document` when anything asks for the preferences UI (a footer link, the reopen button). */
14
+ export const OPEN_EVENT = 'jini:consent-open';
15
+ /** Id of the JSON <script> that carries the PageConfig. */
16
+ export const CONFIG_ID = 'jini-consent-config';
17
+ export const OPTIONAL = ['functional', 'analytics', 'marketing'];
18
+ export const CATEGORIES = ['necessary', ...OPTIONAL];
19
+ export const ACTIONS = ['accept', 'reject', 'save', 'do-not-sell', 'withdraw'];
20
+ /** jini = the built-in banner; headless = "My own" banner; off = anonymous analytics only, no UI. */
21
+ export const BANNER_MODES = ['jini', 'headless', 'off'];
22
+ // ---- Slot kind: browser consent adapter ----
23
+ export const ADAPTER_KIND = 'consent-adapter';
24
+ // ---- Slot kind: server region resolver ----
25
+ export const REGION_KIND = 'region-resolver';
26
+ //# sourceMappingURL=contract.js.map
@@ -0,0 +1,67 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import type { ConsentRecord, ConsentRecordPort } from '../server/receipt.js';
3
+ /** Count is unknown when the host cannot inspect receipt storage. */
4
+ export type ConsentReceiptStorageHealth = {
5
+ writable: boolean;
6
+ count: number | null;
7
+ };
8
+ /** Prepare the same private directory used by receipt writes, check write/search access and count
9
+ * receipt files without reading visitor proof. Filesystem errors propagate to the host's readiness check.
10
+ * This is a current permissions check, not a guarantee against later capacity or I/O failures.
11
+ * @example await readConsentReceiptStorage({ directory: '/site/consent-receipts' })
12
+ * @complexity O(directory entries) time and space; no per-receipt reads or writes. */
13
+ export declare function readConsentReceiptStorage({ directory }: {
14
+ directory: string;
15
+ }, { filesystem }?: {
16
+ filesystem?: Pick<typeof fs, 'mkdir' | 'access' | 'readdir'>;
17
+ }): Promise<ConsentReceiptStorageHealth>;
18
+ /** Atomic writer owns flush/rename/permissions; the host binds its installed platform writer. */
19
+ export interface ConsentFilePorts {
20
+ readText(required: {
21
+ filePath: string;
22
+ }, optional?: Record<string, never>): Promise<string | null>;
23
+ writeJson(required: {
24
+ filePath: string;
25
+ record: ConsentRecord;
26
+ }, optional?: Record<string, never>): Promise<void>;
27
+ /** Preserve evidence outside active receipt lookup. Missing files are already inactive. */
28
+ retire?(required: {
29
+ filePath: string;
30
+ }, optional?: Record<string, never>): Promise<void>;
31
+ }
32
+ /** Host injects the existing platform/fs writer rather than copying its durability lifecycle. */
33
+ export type ConsentAtomicWriter = (required: {
34
+ filePath: string;
35
+ data: unknown;
36
+ }, optional: {
37
+ createParent: boolean;
38
+ mode: number;
39
+ refuseSymlink: boolean;
40
+ }) => Promise<void>;
41
+ /** Publish a flushed staging file with an exclusive hard link, then flush the directory on non-Windows hosts.
42
+ * Filesystem/link failures propagate. No reader ever sees a partially-written proof file.
43
+ * @complexity Startup O(r log r) time/O(r) space; subsequent writes amortized O(1) plus bounded receipt I/O. */
44
+ export declare function createNodeConsentFiles({ atomicWrite }: {
45
+ atomicWrite: ConsentAtomicWriter;
46
+ }, { filesystem, uniqueId, maximumRecords, retentionMs, nowMs, platform }?: {
47
+ filesystem?: Pick<typeof fs, 'link' | 'unlink' | 'open' | 'readdir' | 'stat'>;
48
+ uniqueId?: () => string;
49
+ maximumRecords?: number;
50
+ retentionMs?: number;
51
+ nowMs?: () => number;
52
+ platform?: NodeJS.Platform;
53
+ }): ConsentFilePorts;
54
+ /** Per-site opaque filenames; IDs cannot navigate out of the configured proof directory.
55
+ * One immutable file per choice keeps historic policy versions without schema changes.
56
+ * @complexity O(1) record lookup; publication uses the injected writer's cached capacity/retention inventory.
57
+ * @throws Invalid ID, filesystem and malformed JSON errors; only absence returns null. */
58
+ export declare function createConsentFileRecords({ directory, files }: {
59
+ directory: string;
60
+ files: ConsentFilePorts;
61
+ }, _options?: {}): ConsentRecordPort;
62
+ /** Group temporary IPv6 addresses by /64 using native address validation; mapped IPv4 keeps
63
+ * its IPv4 budget. The host still owns trusted-proxy address selection. @complexity O(1). */
64
+ export declare function consentRateLimitKey({ address }: {
65
+ address: string;
66
+ }, _options?: {}): string;
67
+ //# sourceMappingURL=index.d.ts.map