@cookiemunch/react 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -1
- package/dist/client.d.ts +35 -3
- package/dist/client.js +62 -0
- package/dist/client.js.map +1 -1
- package/dist/helpers.d.ts +18 -1
- package/dist/helpers.js +25 -0
- package/dist/helpers.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,7 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
Every published release, newest first. Dates are the day the version was cut.
|
|
4
4
|
|
|
5
|
-
## 0.
|
|
5
|
+
## 0.8.0 (2026-11-25)
|
|
6
|
+
|
|
7
|
+
- Added: `<ConsentIdentity tokenUrl="/api/…">`: a same-origin route that mints the token server-side and answers `{ token }`, instead of a `getToken` in the browser. A 401 is retried once.
|
|
8
|
+
|
|
9
|
+
## 0.7.0 (2026-11-11)
|
|
10
|
+
|
|
11
|
+
- `onConsentCategory(category, fn)` and the hook `useConsentTransition(category, fn)` call `fn` only when that category changes, with `{ granted, previous, replay, cause }`. A visitor's stored decision is replayed once with `replay: true`.
|
|
12
|
+
|
|
13
|
+
## 0.6.0 (2026-11-05)
|
|
6
14
|
|
|
7
15
|
- `hasConsent(category)` and `onConsentChange(fn)`, moved here from `@cookiemunch/next`, which still exports them.
|
|
8
16
|
|
package/dist/client.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
|
-
import { PublicConsent, Category, CategoryId, ConsentCookieOptions } from './helpers.js';
|
|
3
|
+
import { PublicConsent, Category, CategoryId, ConsentCookieOptions, ConsentTransition } from './helpers.js';
|
|
4
4
|
|
|
5
5
|
interface ConsentProviderProps {
|
|
6
6
|
/** The Cookie Munch site id (required). Injected as `data-cbid` on the embed. */
|
|
@@ -101,7 +101,7 @@ interface CookieDeclarationProps {
|
|
|
101
101
|
id?: string;
|
|
102
102
|
}
|
|
103
103
|
/**
|
|
104
|
-
* The live cookie declaration, for a privacy page in a React / Next.js app
|
|
104
|
+
* The live cookie declaration, for a privacy page in a React / Next.js app.
|
|
105
105
|
*
|
|
106
106
|
* Renders `<div data-cc="declaration">` and lets the embed draw the table into it. The
|
|
107
107
|
* embed fills the element whenever it appears — on first load, after a client-side
|
|
@@ -128,6 +128,38 @@ declare function CookieDeclaration({ emptyText, className, id }: CookieDeclarati
|
|
|
128
128
|
*/
|
|
129
129
|
declare function useBannerInset(edge?: 'bottom' | 'top'): number;
|
|
130
130
|
|
|
131
|
+
/**
|
|
132
|
+
* `onConsentCategory` as a hook: `fn` runs only when `category` changes (and once as a replay when the
|
|
133
|
+
* visitor had already decided). The latest `fn` is always the one called; resubscribes only when the category changes.
|
|
134
|
+
*/
|
|
135
|
+
declare function useConsentTransition(category: string, fn: (t: ConsentTransition) => void): void;
|
|
136
|
+
|
|
137
|
+
interface ConsentIdentityProps {
|
|
138
|
+
/**
|
|
139
|
+
* The signed-in person's id in your app (any stable string), or null/undefined when nobody is signed in.
|
|
140
|
+
* A change re-links; null unlinks this browser.
|
|
141
|
+
*/
|
|
142
|
+
subject: string | null | undefined;
|
|
143
|
+
/**
|
|
144
|
+
* Mints a fresh subject token for `aud: cookiemunch:<cbid>` — with Atlas,
|
|
145
|
+
* `() => getToken({ for: 'cookiemunch', cbid })`. Called on sign-in and every 12 hours while mounted,
|
|
146
|
+
* since a token is valid for 120 seconds only. Resolve null to skip a round.
|
|
147
|
+
*/
|
|
148
|
+
getToken?: () => Promise<string | null | undefined> | string | null | undefined;
|
|
149
|
+
/**
|
|
150
|
+
* Instead of `getToken`: a same-origin route of yours that mints the token server-side and answers
|
|
151
|
+
* `{ token }` to a GET, e.g. `/api/atlas/token/cookiemunch` (LinkHub CM-L14). Sent with the page's
|
|
152
|
+
* cookies; a 401 is retried once, then that round is skipped.
|
|
153
|
+
*/
|
|
154
|
+
tokenUrl?: string;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Links the visitor's consent decision to the signed-in person, so it follows them to their other
|
|
158
|
+
* devices (https://cookiemunch.net/docs/consent-api#linking-a-decision-to-a-signed-in-person).
|
|
159
|
+
* Put it once in the root layout, inside whatever provides the session. Renders nothing.
|
|
160
|
+
*/
|
|
161
|
+
declare function ConsentIdentity({ subject, getToken, tokenUrl }: ConsentIdentityProps): null;
|
|
162
|
+
|
|
131
163
|
interface CookieSettingsLinkProps {
|
|
132
164
|
children?: ReactNode;
|
|
133
165
|
className?: string;
|
|
@@ -142,4 +174,4 @@ interface CookieSettingsLinkProps {
|
|
|
142
174
|
*/
|
|
143
175
|
declare function CookieSettingsLink({ children, className, href }: CookieSettingsLinkProps): react.JSX.Element;
|
|
144
176
|
|
|
145
|
-
export { type ConsentContextValue, ConsentGate, type ConsentGateProps, ConsentProvider, type ConsentProviderProps, CookieDeclaration, type CookieDeclarationProps, CookieSettingsLink, type CookieSettingsLinkProps, type MintedRightsLink, RightsLink, type RightsLinkProps, useBannerInset, useConsent, useConsentCookie, useConsentValue };
|
|
177
|
+
export { type ConsentContextValue, ConsentGate, type ConsentGateProps, ConsentIdentity, type ConsentIdentityProps, ConsentProvider, type ConsentProviderProps, CookieDeclaration, type CookieDeclarationProps, CookieSettingsLink, type CookieSettingsLinkProps, type MintedRightsLink, RightsLink, type RightsLinkProps, useBannerInset, useConsent, useConsentCookie, useConsentTransition, useConsentValue };
|
package/dist/client.js
CHANGED
|
@@ -218,6 +218,66 @@ function useBannerInset(edge = "bottom") {
|
|
|
218
218
|
return useSyncExternalStore2(subscribe2, () => read(edge), () => 0);
|
|
219
219
|
}
|
|
220
220
|
|
|
221
|
+
// src/useConsentTransition.ts
|
|
222
|
+
import { useEffect as useEffect4, useRef as useRef3 } from "react";
|
|
223
|
+
import { onConsentCategory } from "./helpers.js";
|
|
224
|
+
function useConsentTransition(category, fn) {
|
|
225
|
+
const ref = useRef3(fn);
|
|
226
|
+
ref.current = fn;
|
|
227
|
+
useEffect4(() => onConsentCategory(category, (t) => ref.current(t)), [category]);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// src/ConsentIdentity.tsx
|
|
231
|
+
import { useEffect as useEffect5, useRef as useRef4 } from "react";
|
|
232
|
+
var RELINK_MS = 12 * 60 * 60 * 1e3;
|
|
233
|
+
async function fromUrl(url) {
|
|
234
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
235
|
+
const res = await fetch(url, { credentials: "same-origin", headers: { Accept: "application/json" } });
|
|
236
|
+
if (res.status === 401 && attempt === 0) continue;
|
|
237
|
+
if (!res.ok) return null;
|
|
238
|
+
const t = (await res.json())?.token;
|
|
239
|
+
return typeof t === "string" && t ? t : null;
|
|
240
|
+
}
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
function identify(token) {
|
|
244
|
+
const w = window;
|
|
245
|
+
const fd = w.__consent = w.__consent || { q: [] };
|
|
246
|
+
if (fd.version && typeof fd.identify === "function") void fd.identify(token);
|
|
247
|
+
else fd.q?.push(["identify", token]);
|
|
248
|
+
}
|
|
249
|
+
function unlink() {
|
|
250
|
+
window.CookieMunch?.setSyncToken?.(null);
|
|
251
|
+
}
|
|
252
|
+
function ConsentIdentity({ subject, getToken, tokenUrl }) {
|
|
253
|
+
const mint = useRef4(() => null);
|
|
254
|
+
mint.current = getToken ?? (tokenUrl ? () => fromUrl(tokenUrl) : () => null);
|
|
255
|
+
const linked = useRef4(false);
|
|
256
|
+
useEffect5(() => {
|
|
257
|
+
if (!subject) {
|
|
258
|
+
if (linked.current) unlink();
|
|
259
|
+
linked.current = false;
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
linked.current = true;
|
|
263
|
+
let live = true;
|
|
264
|
+
const link = async () => {
|
|
265
|
+
try {
|
|
266
|
+
const token = await mint.current();
|
|
267
|
+
if (live && typeof token === "string" && token) identify(token);
|
|
268
|
+
} catch {
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
void link();
|
|
272
|
+
const timer = setInterval(() => void link(), RELINK_MS);
|
|
273
|
+
return () => {
|
|
274
|
+
live = false;
|
|
275
|
+
clearInterval(timer);
|
|
276
|
+
};
|
|
277
|
+
}, [subject]);
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
|
|
221
281
|
// src/CookieSettingsLink.tsx
|
|
222
282
|
import { jsx as jsx5 } from "react/jsx-runtime";
|
|
223
283
|
function CookieSettingsLink({ children = "Cookie settings", className, href = "#cookie-settings" }) {
|
|
@@ -225,6 +285,7 @@ function CookieSettingsLink({ children = "Cookie settings", className, href = "#
|
|
|
225
285
|
}
|
|
226
286
|
export {
|
|
227
287
|
ConsentGate,
|
|
288
|
+
ConsentIdentity,
|
|
228
289
|
ConsentProvider,
|
|
229
290
|
CookieDeclaration,
|
|
230
291
|
CookieSettingsLink,
|
|
@@ -232,6 +293,7 @@ export {
|
|
|
232
293
|
useBannerInset,
|
|
233
294
|
useConsent,
|
|
234
295
|
useConsentCookie,
|
|
296
|
+
useConsentTransition,
|
|
235
297
|
useConsentValue
|
|
236
298
|
};
|
|
237
299
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ConsentProvider.tsx","../src/context.ts","../src/useConsent.ts","../src/ConsentGate.tsx","../src/useConsentValue.ts","../src/RightsLink.tsx","../src/CookieDeclaration.tsx","../src/useBannerInset.ts","../src/CookieSettingsLink.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type ReactNode } from 'react';\nimport { ConsentContext, EMPTY_CONSENT, type ConsentContextValue } from './context.js';\nimport type { CookieMunchGlobal, PublicConsent } from './helpers.js';\n\n/** Default CDN location of the base browser embed. */\nconst DEFAULT_SRC = 'https://cdn.cookiemunch.net/consent.js';\n/** The <script> id the embed's bootstrap reads via getElementById. */\nconst SCRIPT_ID = 'CookieMunch';\n\nexport interface ConsentProviderProps {\n /** The Cookie Munch site id (required). Injected as `data-cbid` on the embed. */\n cbid: string;\n /** Embed URL. Defaults to the public CDN. */\n src?: string;\n /** Override the API base the embed beacons to (injected as `data-api`). */\n apiBase?: string;\n children: ReactNode;\n}\n\ninterface Snapshot {\n ready: boolean;\n consent: PublicConsent;\n hasResponse: boolean;\n consented: boolean;\n}\n\nconst INITIAL_SNAPSHOT: Snapshot = {\n ready: false,\n consent: EMPTY_CONSENT,\n hasResponse: false,\n consented: false,\n};\n\n/**\n * Locate the embed's <script> tag, injecting it if it isn't already present.\n * The embed self-bootstraps from the tag's `data-*` attributes and, once ready,\n * assigns `window.CookieMunch`.\n */\nfunction ensureEmbedScript(cbid: string, src: string, apiBase: string | undefined): void {\n const existing = document.getElementById(SCRIPT_ID);\n if (existing) return;\n const script = document.createElement('script');\n script.id = SCRIPT_ID;\n script.async = true;\n script.src = src;\n script.setAttribute('data-cbid', cbid);\n if (apiBase) script.setAttribute('data-api', apiBase);\n (document.head || document.documentElement).appendChild(script);\n}\n\n/**\n * Loads the Cookie Munch browser embed from the CDN at runtime and exposes\n * reactive consent state to descendants — a standalone script-tag SDK wrapper\n * that does NOT bundle the proprietary engine.\n *\n * SSR-safe: no `window`/`document` access during render; the script is injected\n * and the global API resolved only inside an effect. Descendants see an\n * all-denied, not-ready snapshot until the embed reports in.\n */\nexport function ConsentProvider({ cbid, src = DEFAULT_SRC, apiBase, children }: ConsentProviderProps) {\n const apiRef = useRef<CookieMunchGlobal | null>(null);\n const [snap, setSnap] = useState<Snapshot>(INITIAL_SNAPSHOT);\n\n useEffect(() => {\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\n\n let disposed = false;\n let offConsentChange: (() => void) | null = null;\n let pollTimer: ReturnType<typeof setInterval> | null = null;\n\n const sync = (api: CookieMunchGlobal) => {\n if (disposed) return;\n setSnap({\n ready: true,\n consent: api.consent,\n hasResponse: api.hasResponse,\n consented: api.consented,\n });\n };\n\n const bind = (api: CookieMunchGlobal) => {\n if (disposed) return;\n apiRef.current = api;\n sync(api);\n offConsentChange = api.onConsentChange(() => sync(api));\n };\n\n // If the embed is already on the page, reuse it immediately.\n if (window.CookieMunch) {\n bind(window.CookieMunch);\n } else {\n ensureEmbedScript(cbid, src, apiBase);\n // The embed sets window.CookieMunch asynchronously (after its remote-config\n // fetch), so poll until it appears, then bind once.\n pollTimer = setInterval(() => {\n if (window.CookieMunch) {\n if (pollTimer) clearInterval(pollTimer);\n pollTimer = null;\n bind(window.CookieMunch);\n }\n }, 50);\n }\n\n return () => {\n disposed = true;\n if (pollTimer) clearInterval(pollTimer);\n offConsentChange?.();\n apiRef.current = null;\n };\n // Re-bind if the site id / source changes.\n }, [cbid, src, apiBase]);\n\n const api = apiRef.current;\n const value: ConsentContextValue = {\n ready: snap.ready,\n consent: snap.consent,\n hasResponse: snap.hasResponse,\n consented: snap.consented,\n acceptAll: () => api?.submitCustomConsent(true, true, true),\n declineAll: () => api?.submitCustomConsent(false, false, false),\n submitCustomConsent: (p, s, m) => api?.submitCustomConsent(p, s, m),\n withdraw: () => api?.withdraw(),\n show: () => api?.show(),\n renew: () => api?.renew(),\n };\n\n return <ConsentContext.Provider value={value}>{children}</ConsentContext.Provider>;\n}\n","import { createContext } from 'react';\nimport type { PublicConsent } from './helpers.js';\n\nexport interface ConsentContextValue {\n ready: boolean;\n consent: PublicConsent;\n hasResponse: boolean;\n consented: boolean;\n acceptAll(): void;\n declineAll(): void;\n submitCustomConsent(preferences: boolean, statistics: boolean, marketing: boolean): void;\n withdraw(): void;\n show(): void;\n renew(): void;\n}\n\nexport const EMPTY_CONSENT: PublicConsent = {\n necessary: true,\n preferences: false,\n statistics: false,\n marketing: false,\n personalizedAds: false,\n basicAds: false,\n adProfiling: false,\n adMeasurement: false,\n stamp: '',\n};\n\n/** null sentinel => used to detect \"called outside a ConsentProvider\". */\nexport const ConsentContext = createContext<ConsentContextValue | null>(null);\n","import { useContext } from 'react';\nimport { ConsentContext, type ConsentContextValue } from './context.js';\n\nexport type { ConsentContextValue };\n\n/** Access reactive consent state + actions. Must be used within a ConsentProvider. */\nexport function useConsent(): ConsentContextValue {\n const ctx = useContext(ConsentContext);\n if (!ctx) {\n throw new Error('useConsent must be used within a <ConsentProvider>.');\n }\n return ctx;\n}\n","import type { ReactNode } from 'react';\nimport type { Category } from './helpers.js';\nimport { useConsent } from './useConsent.js';\n\nexport interface ConsentGateProps {\n category: Exclude<Category, 'necessary'>;\n children: ReactNode;\n fallback?: ReactNode;\n}\n\n/** Renders children only when the given category is granted (else `fallback`). */\nexport function ConsentGate({ category, children, fallback = null }: ConsentGateProps) {\n const { consent } = useConsent();\n return <>{consent[category] ? children : fallback}</>;\n}\n","import { useContext, useEffect, useSyncExternalStore } from 'react';\nimport { ConsentContext } from './context.js';\nimport { consentCookie, isGranted, type CategoryId, type ConsentCookieOptions } from './helpers.js';\n\n/** Window events after which the embed's consent may differ. */\nconst CHANGE_EVENTS = ['CookieMunchOnChange', 'CookieMunchOnAccept', 'CookieMunchOnDecline'];\n\nfunction subscribe(onStoreChange: () => void): () => void {\n if (typeof window === 'undefined') return () => {};\n for (const e of CHANGE_EVENTS) window.addEventListener(e, onStoreChange);\n return () => {\n for (const e of CHANGE_EVENTS) window.removeEventListener(e, onStoreChange);\n };\n}\n\n/**\n * Whether `category` is granted right now — `'preferences'`, `'statistics'`,\n * `'marketing'`, `'necessary'` (always true) or one of your custom category ids — and\n * re-renders when that changes, whatever changed it.\n *\n * `false` until the embed has reported (and during SSR), so gated content never renders\n * ahead of consent. Works inside `<ConsentProvider>` and, when the embed is on the page\n * some other way, without one.\n *\n * const analytics = useConsentValue('statistics');\n */\nexport function useConsentValue(category: CategoryId): boolean {\n const ctx = useContext(ConsentContext);\n const standalone = useSyncExternalStore(\n subscribe,\n () => (typeof window === 'undefined' ? false : isGranted(window.CookieMunch?.consent, category)),\n () => false,\n );\n if (ctx) return ctx.ready ? isGranted(ctx.consent, category) : category === 'necessary';\n return standalone;\n}\n\n/**\n * {@link consentCookie} for a component's lifetime: the cookie is written while `category`\n * is granted and removed when it is not. Pass a stable `value` (or a lazy function); the\n * subscription is re-created when `name`, `category`, `value` or an option changes.\n *\n * useConsentCookie('affiliate_id', 'marketing', ref, { maxAgeDays: 30 });\n */\nexport function useConsentCookie(\n name: string,\n category: CategoryId,\n value: string | (() => string),\n opts: ConsentCookieOptions = {},\n): void {\n const { maxAgeDays, path, domain, sameSite, secure } = opts;\n useEffect(\n () => consentCookie(name, category, value, { maxAgeDays, path, domain, sameSite, secure }),\n [name, category, value, maxAgeDays, path, domain, sameSite, secure],\n );\n}\n","import { useCallback, useState, type MouseEvent, type ReactNode } from 'react';\nimport { isRightsLinkUrl } from './helpers.js';\n\n/** What `mint` may resolve to: the mint response from `POST /v1/sites/{cbid}/rights-links`, or just its `url`. */\nexport type MintedRightsLink = string | { url: string; customDomain?: string | null };\n\nexport interface RightsLinkProps {\n /**\n * Mints a single-use account link for the signed-in person — a server action (or an endpoint\n * you call) that holds a `dsar:rights-links` key and calls `POST /v1/sites/{cbid}/rights-links`.\n * Never put the key in the browser. Called on click, not on render: links are single-use and\n * expire (15 minutes by default), so one minted per page view would mostly go to waste.\n */\n mint: () => Promise<MintedRightsLink>;\n /** Where the link goes before a mint, and when one fails: the plain hosted form (the email-code flow), e.g. `https://cookiemunch.net/r/<cbid>`. */\n fallbackHref?: string;\n children?: ReactNode;\n className?: string;\n /** Called when a mint fails or returns a URL that is not a rights link, before falling back. */\n onError?: (error: Error) => void;\n}\n\n/**\n * \"Your privacy rights\" for a signed-in person: on click it mints an account link (their email is\n * filled in and locked, the email-code step skipped) and opens it. Plain anchor markup, so it\n * renders the same on the server and the client.\n */\nexport function RightsLink({ mint, fallbackHref, children = 'Your privacy rights', className, onError }: RightsLinkProps) {\n const [busy, setBusy] = useState(false);\n const onClick = useCallback(\n async (e: MouseEvent<HTMLAnchorElement>) => {\n // A modified click (new tab, download) keeps the fallback: a minted link is for this tab.\n if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;\n e.preventDefault();\n if (busy) return;\n setBusy(true);\n try {\n const got = await mint();\n const url = typeof got === 'string' ? got : got.url;\n const customDomain = typeof got === 'string' ? undefined : got.customDomain;\n if (!isRightsLinkUrl(url, customDomain)) throw new Error(`not a rights link: ${url}`);\n window.location.assign(url);\n } catch (err) {\n onError?.(err instanceof Error ? err : new Error(String(err)));\n if (fallbackHref) window.location.assign(fallbackHref);\n } finally {\n setBusy(false);\n }\n },\n [busy, mint, fallbackHref, onError],\n );\n return (\n <a href={fallbackHref ?? '#'} className={className} onClick={onClick} aria-busy={busy || undefined}>\n {children}\n </a>\n );\n}\n","import { useEffect, useRef } from 'react';\n\nexport interface CookieDeclarationProps {\n /** Shown when the site has no cookies to list yet (the mount's `data-empty`). */\n emptyText?: string;\n className?: string;\n id?: string;\n}\n\n/**\n * Stable across renders: React rewrites `innerHTML` only when the `__html` string changes,\n * so an empty string that never changes means React never touches what the embed drew.\n */\nconst EMPTY = { __html: '' };\n\n/**\n * The live cookie declaration, for a privacy page in a React / Next.js app (CKM-S-10).\n *\n * Renders `<div data-cc=\"declaration\">` and lets the embed draw the table into it. The\n * embed fills the element whenever it appears — on first load, after a client-side\n * navigation, or before hydration on a server-rendered page — so the element's children\n * belong to the embed, not to React:\n * - `dangerouslySetInnerHTML` with a constant empty string tells React it does not own\n * the children, so it neither hydrates nor replaces them;\n * - `suppressHydrationWarning` covers the one difference React would otherwise report:\n * the server sent an empty element and the embed may already have filled it.\n * After mount it asks the embed to draw this element, in case it was added after load.\n */\nexport function CookieDeclaration({ emptyText, className, id }: CookieDeclarationProps) {\n const ref = useRef<HTMLDivElement>(null);\n useEffect(() => {\n const el = ref.current;\n const api = typeof window !== 'undefined' ? window.CookieMunch : undefined;\n if (el && !el.hasChildNodes()) void api?.renderDeclaration?.(el)?.catch?.(() => {});\n }, []);\n return (\n <div\n ref={ref}\n id={id}\n className={className}\n data-cc=\"declaration\"\n {...(emptyText !== undefined ? { 'data-empty': emptyText } : {})}\n suppressHydrationWarning\n dangerouslySetInnerHTML={EMPTY}\n />\n );\n}\n","import { useSyncExternalStore } from 'react';\n\nfunction subscribe(onStoreChange: () => void): () => void {\n if (typeof window === 'undefined') return () => {};\n window.addEventListener('fd:layout', onStoreChange);\n return () => window.removeEventListener('fd:layout', onStoreChange);\n}\n\nfunction read(edge: 'bottom' | 'top'): number {\n if (typeof document === 'undefined') return 0;\n const v = document.documentElement.style.getPropertyValue(`--cookiemunch-inset-${edge}`);\n const n = parseFloat(v);\n return Number.isFinite(n) ? n : 0;\n}\n\n/**\n * How many pixels of the viewport's bottom (or top) edge the consent bar covers right now — 0\n * when no bar shows — re-rendering on every change. For floating UI the CSS variable\n * `--cookiemunch-inset-bottom` (or the vendor-neutral `--fd-safe-bottom`) does the same job\n * without a render; use this when the offset is computed in JavaScript.\n *\n * const inset = useBannerInset();\n * <ChatButton style={{ bottom: 20 + inset }} />\n *\n * 0 during SSR. Works with or without `<ConsentProvider>`.\n */\nexport function useBannerInset(edge: 'bottom' | 'top' = 'bottom'): number {\n return useSyncExternalStore(subscribe, () => read(edge), () => 0);\n}\n","import type { ReactNode } from 'react';\n\nexport interface CookieSettingsLinkProps {\n children?: ReactNode;\n className?: string;\n /** Where the link points before the embed has loaded (or with scripts off). Default `#cookie-settings`. */\n href?: string;\n}\n\n/**\n * \"Cookie settings\": reopens the visitor's consent choices. It is plain markup — an anchor with\n * `data-cc=\"show-settings\"`, which the embed's own click listener turns into\n * `CookieMunch.showSettings()` — so it renders identically on the server and the client, needs no\n * `<ConsentProvider>`, and opens the panel exactly once (no second handler of its own).\n */\nexport function CookieSettingsLink({ children = 'Cookie settings', className, href = '#cookie-settings' }: CookieSettingsLinkProps) {\n return (\n <a href={href} className={className} data-cc=\"show-settings\">\n {children}\n </a>\n );\n}\n"],"mappings":";;;AAAA,SAAS,WAAW,QAAQ,gBAAgC;;;ACA5D,SAAS,qBAAqB;AAgBvB,IAAM,gBAA+B;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,WAAQ;AAAA,MACP,GAAI,cAAc,SAAY,EAAE,cAAc,UAAU,IAAI,CAAC;AAAA,MAC9D,0BAAwB;AAAA,MACxB,yBAAyB;AAAA;AAAA,EAC3B;AAEJ;;;AC9CA,SAAS,wBAAAC,6BAA4B;AAErC,SAASC,WAAU,eAAuC;AACxD,MAAI,OAAO,WAAW,YAAa,QAAO,MAAM;AAAA,EAAC;AACjD,SAAO,iBAAiB,aAAa,aAAa;AAClD,SAAO,MAAM,OAAO,oBAAoB,aAAa,aAAa;AACpE;AAEA,SAAS,KAAK,MAAgC;AAC5C,MAAI,OAAO,aAAa,YAAa,QAAO;AAC5C,QAAM,IAAI,SAAS,gBAAgB,MAAM,iBAAiB,uBAAuB,IAAI,EAAE;AACvF,QAAM,IAAI,WAAW,CAAC;AACtB,SAAO,OAAO,SAAS,CAAC,IAAI,IAAI;AAClC;AAaO,SAAS,eAAe,OAAyB,UAAkB;AACxE,SAAOD,sBAAqBC,YAAW,MAAM,KAAK,IAAI,GAAG,MAAM,CAAC;AAClE;;;ACXI,gBAAAC,YAAA;AAFG,SAAS,mBAAmB,EAAE,WAAW,mBAAmB,WAAW,OAAO,mBAAmB,GAA4B;AAClI,SACE,gBAAAA,KAAC,OAAE,MAAY,WAAsB,WAAQ,iBAC1C,UACH;AAEJ;","names":["api","jsx","useContext","useEffect","useContext","useEffect","useState","jsx","useEffect","useRef","jsx","useSyncExternalStore","subscribe","jsx"]}
|
|
1
|
+
{"version":3,"sources":["../src/ConsentProvider.tsx","../src/context.ts","../src/useConsent.ts","../src/ConsentGate.tsx","../src/useConsentValue.ts","../src/RightsLink.tsx","../src/CookieDeclaration.tsx","../src/useBannerInset.ts","../src/useConsentTransition.ts","../src/ConsentIdentity.tsx","../src/CookieSettingsLink.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type ReactNode } from 'react';\nimport { ConsentContext, EMPTY_CONSENT, type ConsentContextValue } from './context.js';\nimport type { CookieMunchGlobal, PublicConsent } from './helpers.js';\n\n/** Default CDN location of the base browser embed. */\nconst DEFAULT_SRC = 'https://cdn.cookiemunch.net/consent.js';\n/** The <script> id the embed's bootstrap reads via getElementById. */\nconst SCRIPT_ID = 'CookieMunch';\n\nexport interface ConsentProviderProps {\n /** The Cookie Munch site id (required). Injected as `data-cbid` on the embed. */\n cbid: string;\n /** Embed URL. Defaults to the public CDN. */\n src?: string;\n /** Override the API base the embed beacons to (injected as `data-api`). */\n apiBase?: string;\n children: ReactNode;\n}\n\ninterface Snapshot {\n ready: boolean;\n consent: PublicConsent;\n hasResponse: boolean;\n consented: boolean;\n}\n\nconst INITIAL_SNAPSHOT: Snapshot = {\n ready: false,\n consent: EMPTY_CONSENT,\n hasResponse: false,\n consented: false,\n};\n\n/**\n * Locate the embed's <script> tag, injecting it if it isn't already present.\n * The embed self-bootstraps from the tag's `data-*` attributes and, once ready,\n * assigns `window.CookieMunch`.\n */\nfunction ensureEmbedScript(cbid: string, src: string, apiBase: string | undefined): void {\n const existing = document.getElementById(SCRIPT_ID);\n if (existing) return;\n const script = document.createElement('script');\n script.id = SCRIPT_ID;\n script.async = true;\n script.src = src;\n script.setAttribute('data-cbid', cbid);\n if (apiBase) script.setAttribute('data-api', apiBase);\n (document.head || document.documentElement).appendChild(script);\n}\n\n/**\n * Loads the Cookie Munch browser embed from the CDN at runtime and exposes\n * reactive consent state to descendants — a standalone script-tag SDK wrapper\n * that does NOT bundle the proprietary engine.\n *\n * SSR-safe: no `window`/`document` access during render; the script is injected\n * and the global API resolved only inside an effect. Descendants see an\n * all-denied, not-ready snapshot until the embed reports in.\n */\nexport function ConsentProvider({ cbid, src = DEFAULT_SRC, apiBase, children }: ConsentProviderProps) {\n const apiRef = useRef<CookieMunchGlobal | null>(null);\n const [snap, setSnap] = useState<Snapshot>(INITIAL_SNAPSHOT);\n\n useEffect(() => {\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\n\n let disposed = false;\n let offConsentChange: (() => void) | null = null;\n let pollTimer: ReturnType<typeof setInterval> | null = null;\n\n const sync = (api: CookieMunchGlobal) => {\n if (disposed) return;\n setSnap({\n ready: true,\n consent: api.consent,\n hasResponse: api.hasResponse,\n consented: api.consented,\n });\n };\n\n const bind = (api: CookieMunchGlobal) => {\n if (disposed) return;\n apiRef.current = api;\n sync(api);\n offConsentChange = api.onConsentChange(() => sync(api));\n };\n\n // If the embed is already on the page, reuse it immediately.\n if (window.CookieMunch) {\n bind(window.CookieMunch);\n } else {\n ensureEmbedScript(cbid, src, apiBase);\n // The embed sets window.CookieMunch asynchronously (after its remote-config\n // fetch), so poll until it appears, then bind once.\n pollTimer = setInterval(() => {\n if (window.CookieMunch) {\n if (pollTimer) clearInterval(pollTimer);\n pollTimer = null;\n bind(window.CookieMunch);\n }\n }, 50);\n }\n\n return () => {\n disposed = true;\n if (pollTimer) clearInterval(pollTimer);\n offConsentChange?.();\n apiRef.current = null;\n };\n // Re-bind if the site id / source changes.\n }, [cbid, src, apiBase]);\n\n const api = apiRef.current;\n const value: ConsentContextValue = {\n ready: snap.ready,\n consent: snap.consent,\n hasResponse: snap.hasResponse,\n consented: snap.consented,\n acceptAll: () => api?.submitCustomConsent(true, true, true),\n declineAll: () => api?.submitCustomConsent(false, false, false),\n submitCustomConsent: (p, s, m) => api?.submitCustomConsent(p, s, m),\n withdraw: () => api?.withdraw(),\n show: () => api?.show(),\n renew: () => api?.renew(),\n };\n\n return <ConsentContext.Provider value={value}>{children}</ConsentContext.Provider>;\n}\n","import { createContext } from 'react';\nimport type { PublicConsent } from './helpers.js';\n\nexport interface ConsentContextValue {\n ready: boolean;\n consent: PublicConsent;\n hasResponse: boolean;\n consented: boolean;\n acceptAll(): void;\n declineAll(): void;\n submitCustomConsent(preferences: boolean, statistics: boolean, marketing: boolean): void;\n withdraw(): void;\n show(): void;\n renew(): void;\n}\n\nexport const EMPTY_CONSENT: PublicConsent = {\n necessary: true,\n preferences: false,\n statistics: false,\n marketing: false,\n personalizedAds: false,\n basicAds: false,\n adProfiling: false,\n adMeasurement: false,\n stamp: '',\n};\n\n/** null sentinel => used to detect \"called outside a ConsentProvider\". */\nexport const ConsentContext = createContext<ConsentContextValue | null>(null);\n","import { useContext } from 'react';\nimport { ConsentContext, type ConsentContextValue } from './context.js';\n\nexport type { ConsentContextValue };\n\n/** Access reactive consent state + actions. Must be used within a ConsentProvider. */\nexport function useConsent(): ConsentContextValue {\n const ctx = useContext(ConsentContext);\n if (!ctx) {\n throw new Error('useConsent must be used within a <ConsentProvider>.');\n }\n return ctx;\n}\n","import type { ReactNode } from 'react';\nimport type { Category } from './helpers.js';\nimport { useConsent } from './useConsent.js';\n\nexport interface ConsentGateProps {\n category: Exclude<Category, 'necessary'>;\n children: ReactNode;\n fallback?: ReactNode;\n}\n\n/** Renders children only when the given category is granted (else `fallback`). */\nexport function ConsentGate({ category, children, fallback = null }: ConsentGateProps) {\n const { consent } = useConsent();\n return <>{consent[category] ? children : fallback}</>;\n}\n","import { useContext, useEffect, useSyncExternalStore } from 'react';\nimport { ConsentContext } from './context.js';\nimport { consentCookie, isGranted, type CategoryId, type ConsentCookieOptions } from './helpers.js';\n\n/** Window events after which the embed's consent may differ. */\nconst CHANGE_EVENTS = ['CookieMunchOnChange', 'CookieMunchOnAccept', 'CookieMunchOnDecline'];\n\nfunction subscribe(onStoreChange: () => void): () => void {\n if (typeof window === 'undefined') return () => {};\n for (const e of CHANGE_EVENTS) window.addEventListener(e, onStoreChange);\n return () => {\n for (const e of CHANGE_EVENTS) window.removeEventListener(e, onStoreChange);\n };\n}\n\n/**\n * Whether `category` is granted right now — `'preferences'`, `'statistics'`,\n * `'marketing'`, `'necessary'` (always true) or one of your custom category ids — and\n * re-renders when that changes, whatever changed it.\n *\n * `false` until the embed has reported (and during SSR), so gated content never renders\n * ahead of consent. Works inside `<ConsentProvider>` and, when the embed is on the page\n * some other way, without one.\n *\n * const analytics = useConsentValue('statistics');\n */\nexport function useConsentValue(category: CategoryId): boolean {\n const ctx = useContext(ConsentContext);\n const standalone = useSyncExternalStore(\n subscribe,\n () => (typeof window === 'undefined' ? false : isGranted(window.CookieMunch?.consent, category)),\n () => false,\n );\n if (ctx) return ctx.ready ? isGranted(ctx.consent, category) : category === 'necessary';\n return standalone;\n}\n\n/**\n * {@link consentCookie} for a component's lifetime: the cookie is written while `category`\n * is granted and removed when it is not. Pass a stable `value` (or a lazy function); the\n * subscription is re-created when `name`, `category`, `value` or an option changes.\n *\n * useConsentCookie('affiliate_id', 'marketing', ref, { maxAgeDays: 30 });\n */\nexport function useConsentCookie(\n name: string,\n category: CategoryId,\n value: string | (() => string),\n opts: ConsentCookieOptions = {},\n): void {\n const { maxAgeDays, path, domain, sameSite, secure } = opts;\n useEffect(\n () => consentCookie(name, category, value, { maxAgeDays, path, domain, sameSite, secure }),\n [name, category, value, maxAgeDays, path, domain, sameSite, secure],\n );\n}\n","import { useCallback, useState, type MouseEvent, type ReactNode } from 'react';\nimport { isRightsLinkUrl } from './helpers.js';\n\n/** What `mint` may resolve to: the mint response from `POST /v1/sites/{cbid}/rights-links`, or just its `url`. */\nexport type MintedRightsLink = string | { url: string; customDomain?: string | null };\n\nexport interface RightsLinkProps {\n /**\n * Mints a single-use account link for the signed-in person — a server action (or an endpoint\n * you call) that holds a `dsar:rights-links` key and calls `POST /v1/sites/{cbid}/rights-links`.\n * Never put the key in the browser. Called on click, not on render: links are single-use and\n * expire (15 minutes by default), so one minted per page view would mostly go to waste.\n */\n mint: () => Promise<MintedRightsLink>;\n /** Where the link goes before a mint, and when one fails: the plain hosted form (the email-code flow), e.g. `https://cookiemunch.net/r/<cbid>`. */\n fallbackHref?: string;\n children?: ReactNode;\n className?: string;\n /** Called when a mint fails or returns a URL that is not a rights link, before falling back. */\n onError?: (error: Error) => void;\n}\n\n/**\n * \"Your privacy rights\" for a signed-in person: on click it mints an account link (their email is\n * filled in and locked, the email-code step skipped) and opens it. Plain anchor markup, so it\n * renders the same on the server and the client.\n */\nexport function RightsLink({ mint, fallbackHref, children = 'Your privacy rights', className, onError }: RightsLinkProps) {\n const [busy, setBusy] = useState(false);\n const onClick = useCallback(\n async (e: MouseEvent<HTMLAnchorElement>) => {\n // A modified click (new tab, download) keeps the fallback: a minted link is for this tab.\n if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;\n e.preventDefault();\n if (busy) return;\n setBusy(true);\n try {\n const got = await mint();\n const url = typeof got === 'string' ? got : got.url;\n const customDomain = typeof got === 'string' ? undefined : got.customDomain;\n if (!isRightsLinkUrl(url, customDomain)) throw new Error(`not a rights link: ${url}`);\n window.location.assign(url);\n } catch (err) {\n onError?.(err instanceof Error ? err : new Error(String(err)));\n if (fallbackHref) window.location.assign(fallbackHref);\n } finally {\n setBusy(false);\n }\n },\n [busy, mint, fallbackHref, onError],\n );\n return (\n <a href={fallbackHref ?? '#'} className={className} onClick={onClick} aria-busy={busy || undefined}>\n {children}\n </a>\n );\n}\n","import { useEffect, useRef } from 'react';\n\nexport interface CookieDeclarationProps {\n /** Shown when the site has no cookies to list yet (the mount's `data-empty`). */\n emptyText?: string;\n className?: string;\n id?: string;\n}\n\n/**\n * Stable across renders: React rewrites `innerHTML` only when the `__html` string changes,\n * so an empty string that never changes means React never touches what the embed drew.\n */\nconst EMPTY = { __html: '' };\n\n/**\n * The live cookie declaration, for a privacy page in a React / Next.js app.\n *\n * Renders `<div data-cc=\"declaration\">` and lets the embed draw the table into it. The\n * embed fills the element whenever it appears — on first load, after a client-side\n * navigation, or before hydration on a server-rendered page — so the element's children\n * belong to the embed, not to React:\n * - `dangerouslySetInnerHTML` with a constant empty string tells React it does not own\n * the children, so it neither hydrates nor replaces them;\n * - `suppressHydrationWarning` covers the one difference React would otherwise report:\n * the server sent an empty element and the embed may already have filled it.\n * After mount it asks the embed to draw this element, in case it was added after load.\n */\nexport function CookieDeclaration({ emptyText, className, id }: CookieDeclarationProps) {\n const ref = useRef<HTMLDivElement>(null);\n useEffect(() => {\n const el = ref.current;\n const api = typeof window !== 'undefined' ? window.CookieMunch : undefined;\n if (el && !el.hasChildNodes()) void api?.renderDeclaration?.(el)?.catch?.(() => {});\n }, []);\n return (\n <div\n ref={ref}\n id={id}\n className={className}\n data-cc=\"declaration\"\n {...(emptyText !== undefined ? { 'data-empty': emptyText } : {})}\n suppressHydrationWarning\n dangerouslySetInnerHTML={EMPTY}\n />\n );\n}\n","import { useSyncExternalStore } from 'react';\n\nfunction subscribe(onStoreChange: () => void): () => void {\n if (typeof window === 'undefined') return () => {};\n window.addEventListener('fd:layout', onStoreChange);\n return () => window.removeEventListener('fd:layout', onStoreChange);\n}\n\nfunction read(edge: 'bottom' | 'top'): number {\n if (typeof document === 'undefined') return 0;\n const v = document.documentElement.style.getPropertyValue(`--cookiemunch-inset-${edge}`);\n const n = parseFloat(v);\n return Number.isFinite(n) ? n : 0;\n}\n\n/**\n * How many pixels of the viewport's bottom (or top) edge the consent bar covers right now — 0\n * when no bar shows — re-rendering on every change. For floating UI the CSS variable\n * `--cookiemunch-inset-bottom` (or the vendor-neutral `--fd-safe-bottom`) does the same job\n * without a render; use this when the offset is computed in JavaScript.\n *\n * const inset = useBannerInset();\n * <ChatButton style={{ bottom: 20 + inset }} />\n *\n * 0 during SSR. Works with or without `<ConsentProvider>`.\n */\nexport function useBannerInset(edge: 'bottom' | 'top' = 'bottom'): number {\n return useSyncExternalStore(subscribe, () => read(edge), () => 0);\n}\n","import { useEffect, useRef } from 'react';\nimport { onConsentCategory, type ConsentTransition } from './helpers.js';\n\n/**\n * `onConsentCategory` as a hook: `fn` runs only when `category` changes (and once as a replay when the\n * visitor had already decided). The latest `fn` is always the one called; resubscribes only when the category changes.\n */\nexport function useConsentTransition(category: string, fn: (t: ConsentTransition) => void): void {\n const ref = useRef(fn);\n ref.current = fn;\n useEffect(() => onConsentCategory(category, (t) => ref.current(t)), [category]);\n}\n","import { useEffect, useRef } from 'react';\n\n/** The sync token identify() earns lasts a day (server IDENTITY_TOKEN_TTL_MS); re-link well before it lapses. */\nconst RELINK_MS = 12 * 60 * 60 * 1000;\n\nexport interface ConsentIdentityProps {\n /**\n * The signed-in person's id in your app (any stable string), or null/undefined when nobody is signed in.\n * A change re-links; null unlinks this browser.\n */\n subject: string | null | undefined;\n /**\n * Mints a fresh subject token for `aud: cookiemunch:<cbid>` — with Atlas,\n * `() => getToken({ for: 'cookiemunch', cbid })`. Called on sign-in and every 12 hours while mounted,\n * since a token is valid for 120 seconds only. Resolve null to skip a round.\n */\n getToken?: () => Promise<string | null | undefined> | string | null | undefined;\n /**\n * Instead of `getToken`: a same-origin route of yours that mints the token server-side and answers\n * `{ token }` to a GET, e.g. `/api/atlas/token/cookiemunch` (LinkHub CM-L14). Sent with the page's\n * cookies; a 401 is retried once, then that round is skipped.\n */\n tokenUrl?: string;\n}\n\nasync function fromUrl(url: string): Promise<string | null> {\n for (let attempt = 0; attempt < 2; attempt++) {\n const res = await fetch(url, { credentials: 'same-origin', headers: { Accept: 'application/json' } });\n if (res.status === 401 && attempt === 0) continue;\n if (!res.ok) return null;\n const t = ((await res.json()) as { token?: unknown } | null)?.token;\n return typeof t === 'string' && t ? t : null;\n }\n return null;\n}\n\ntype Queue = { q?: unknown[]; version?: unknown; identify?: (token: string) => unknown };\n\nfunction identify(token: string): void {\n const w = window as unknown as { __consent?: Queue };\n const fd = (w.__consent = w.__consent || { q: [] });\n // Before the embed loads, the call waits in the queue and is replayed in order.\n if (fd.version && typeof fd.identify === 'function') void fd.identify(token);\n else fd.q?.push(['identify', token]);\n}\n\nfunction unlink(): void {\n (window as unknown as { CookieMunch?: { setSyncToken?: (t: string | null) => void } }).CookieMunch?.setSyncToken?.(null);\n}\n\n/**\n * Links the visitor's consent decision to the signed-in person, so it follows them to their other\n * devices (https://cookiemunch.net/docs/consent-api#linking-a-decision-to-a-signed-in-person).\n * Put it once in the root layout, inside whatever provides the session. Renders nothing.\n */\nexport function ConsentIdentity({ subject, getToken, tokenUrl }: ConsentIdentityProps): null {\n const mint = useRef<() => unknown>(() => null);\n mint.current = getToken ?? (tokenUrl ? () => fromUrl(tokenUrl) : () => null);\n const linked = useRef(false);\n useEffect(() => {\n // Unlink only on sign-out: an anonymous first render must not clear a sync token set another way.\n if (!subject) {\n if (linked.current) unlink();\n linked.current = false;\n return;\n }\n linked.current = true;\n let live = true;\n const link = async (): Promise<void> => {\n try {\n const token = await mint.current();\n if (live && typeof token === 'string' && token) identify(token);\n } catch {\n // A failed mint links nothing; the next round (or the next sign-in) tries again.\n }\n };\n void link();\n const timer = setInterval(() => void link(), RELINK_MS);\n return () => {\n live = false;\n clearInterval(timer);\n };\n }, [subject]);\n return null;\n}\n","import type { ReactNode } from 'react';\n\nexport interface CookieSettingsLinkProps {\n children?: ReactNode;\n className?: string;\n /** Where the link points before the embed has loaded (or with scripts off). Default `#cookie-settings`. */\n href?: string;\n}\n\n/**\n * \"Cookie settings\": reopens the visitor's consent choices. It is plain markup — an anchor with\n * `data-cc=\"show-settings\"`, which the embed's own click listener turns into\n * `CookieMunch.showSettings()` — so it renders identically on the server and the client, needs no\n * `<ConsentProvider>`, and opens the panel exactly once (no second handler of its own).\n */\nexport function CookieSettingsLink({ children = 'Cookie settings', className, href = '#cookie-settings' }: CookieSettingsLinkProps) {\n return (\n <a href={href} className={className} data-cc=\"show-settings\">\n {children}\n </a>\n );\n}\n"],"mappings":";;;AAAA,SAAS,WAAW,QAAQ,gBAAgC;;;ACA5D,SAAS,qBAAqB;AAgBvB,IAAM,gBAA+B;AAAA,EAC1C,WAAW;AAAA,EACX,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,UAAU;AAAA,EACV,aAAa;AAAA,EACb,eAAe;AAAA,EACf,OAAO;AACT;AAGO,IAAM,iBAAiB,cAA0C,IAAI;;;ADiGnE;AAzHT,IAAM,cAAc;AAEpB,IAAM,YAAY;AAmBlB,IAAM,mBAA6B;AAAA,EACjC,OAAO;AAAA,EACP,SAAS;AAAA,EACT,aAAa;AAAA,EACb,WAAW;AACb;AAOA,SAAS,kBAAkB,MAAc,KAAa,SAAm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AAsF,aAAa,eAAe,IAAI;AACzH;AAOO,SAAS,gBAAgB,EAAE,SAAS,UAAU,SAAS,GAA+B;AAC3F,QAAM,OAAOA,QAAsB,MAAM,IAAI;AAC7C,OAAK,UAAU,aAAa,WAAW,MAAM,QAAQ,QAAQ,IAAI,MAAM;AACvE,QAAM,SAASA,QAAO,KAAK;AAC3B,EAAAD,WAAU,MAAM;AAEd,QAAI,CAAC,SAAS;AACZ,UAAI,OAAO,QAAS,QAAO;AAC3B,aAAO,UAAU;AACjB;AAAA,IACF;AACA,WAAO,UAAU;AACjB,QAAI,OAAO;AACX,UAAM,OAAO,YAA2B;AACtC,UAAI;AACF,cAAM,QAAQ,MAAM,KAAK,QAAQ;AACjC,YAAI,QAAQ,OAAO,UAAU,YAAY,MAAO,UAAS,KAAK;AAAA,MAChE,QAAQ;AAAA,MAER;AAAA,IACF;AACA,SAAK,KAAK;AACV,UAAM,QAAQ,YAAY,MAAM,KAAK,KAAK,GAAG,SAAS;AACtD,WAAO,MAAM;AACX,aAAO;AACP,oBAAc,KAAK;AAAA,IACrB;AAAA,EACF,GAAG,CAAC,OAAO,CAAC;AACZ,SAAO;AACT;;;ACnEI,gBAAAE,YAAA;AAFG,SAAS,mBAAmB,EAAE,WAAW,mBAAmB,WAAW,OAAO,mBAAmB,GAA4B;AAClI,SACE,gBAAAA,KAAC,OAAE,MAAY,WAAsB,WAAQ,iBAC1C,UACH;AAEJ;","names":["api","jsx","useContext","useEffect","useContext","useEffect","useState","jsx","useEffect","useRef","jsx","useSyncExternalStore","subscribe","useEffect","useRef","useEffect","useRef","jsx"]}
|
package/dist/helpers.d.ts
CHANGED
|
@@ -56,6 +56,23 @@ declare function hasConsent(category: string): boolean;
|
|
|
56
56
|
* Returns the unsubscribe. Does nothing on the server.
|
|
57
57
|
*/
|
|
58
58
|
declare function onConsentChange(fn: (consent: Consent) => void): () => void;
|
|
59
|
+
/** What `onConsentCategory` hands its callback. */
|
|
60
|
+
interface ConsentTransition {
|
|
61
|
+
/** The category's state now. */
|
|
62
|
+
granted: boolean;
|
|
63
|
+
/** Its state before this call: undefined on the first call (no decision seen yet in this page). */
|
|
64
|
+
previous: boolean | undefined;
|
|
65
|
+
/** True for the first call when the visitor had already decided before you subscribed: start what was granted, nothing changed. */
|
|
66
|
+
replay: boolean;
|
|
67
|
+
/** Why it changed, as the embed's change event says (`banner`, `api`, `withdraw`…); `replay` for a replay. */
|
|
68
|
+
cause: string;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Calls `fn` only when `category` actually changes: once straight away as a replay when the visitor
|
|
72
|
+
* has already decided, then on each grant or withdrawal, never twice for the same state. Start a
|
|
73
|
+
* vendor on `granted`, stop it when `!granted && previous`. Returns the unsubscribe; nothing on the server.
|
|
74
|
+
*/
|
|
75
|
+
declare function onConsentCategory(category: string, fn: (t: ConsentTransition) => void): () => void;
|
|
59
76
|
|
|
60
77
|
/**
|
|
61
78
|
* Read the embed's consent cookie on the server, where `document` does not exist — a Server
|
|
@@ -175,4 +192,4 @@ declare global {
|
|
|
175
192
|
*/
|
|
176
193
|
declare function isRightsLinkUrl(url: string, customDomain?: string | null): boolean;
|
|
177
194
|
|
|
178
|
-
export { CONSENT_COOKIE_NAME, type Category, type CategoryId, type ConsentCookieOptions, type ConsentCookieState, type CookieMunchCategories, type CookieMunchGlobal, type PublicConsent, consentCookie, hasConsent, isGranted, isRightsLinkUrl, onConsentChange, parseConsentCookie };
|
|
195
|
+
export { CONSENT_COOKIE_NAME, type Category, type CategoryId, type ConsentCookieOptions, type ConsentCookieState, type ConsentTransition, type CookieMunchCategories, type CookieMunchGlobal, type PublicConsent, consentCookie, hasConsent, isGranted, isRightsLinkUrl, onConsentCategory, onConsentChange, parseConsentCookie };
|
package/dist/helpers.js
CHANGED
|
@@ -82,6 +82,30 @@ function onConsentChange(fn) {
|
|
|
82
82
|
window.removeEventListener("CookieMunchOnChange", onChange);
|
|
83
83
|
};
|
|
84
84
|
}
|
|
85
|
+
function onConsentCategory(category, fn) {
|
|
86
|
+
if (typeof window === "undefined") return () => {
|
|
87
|
+
};
|
|
88
|
+
let active = true;
|
|
89
|
+
let last;
|
|
90
|
+
const emit = (consent, cause, replay) => {
|
|
91
|
+
const granted = category === "necessary" || isGranted(consent, category);
|
|
92
|
+
if (!active || granted === last) return;
|
|
93
|
+
const previous = last;
|
|
94
|
+
last = granted;
|
|
95
|
+
fn({ granted, previous, replay, cause });
|
|
96
|
+
};
|
|
97
|
+
const onChange = (e) => {
|
|
98
|
+
const d = e.detail;
|
|
99
|
+
if (d?.consent) emit(d.consent, typeof d.cause === "string" ? d.cause : "change", false);
|
|
100
|
+
};
|
|
101
|
+
window.addEventListener("CookieMunchOnChange", onChange);
|
|
102
|
+
const already = decided();
|
|
103
|
+
if (already) queueMicrotask(() => emit(already, "replay", true));
|
|
104
|
+
return () => {
|
|
105
|
+
active = false;
|
|
106
|
+
window.removeEventListener("CookieMunchOnChange", onChange);
|
|
107
|
+
};
|
|
108
|
+
}
|
|
85
109
|
|
|
86
110
|
// src/consent-parse.ts
|
|
87
111
|
var CONSENT_COOKIE_NAME = "CookieMunch";
|
|
@@ -141,6 +165,7 @@ export {
|
|
|
141
165
|
hasConsent,
|
|
142
166
|
isGranted,
|
|
143
167
|
isRightsLinkUrl,
|
|
168
|
+
onConsentCategory,
|
|
144
169
|
onConsentChange,
|
|
145
170
|
parseConsentCookie
|
|
146
171
|
};
|
package/dist/helpers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/consent-cookie.ts","../src/consent-helpers.ts","../src/consent-parse.ts","../src/helpers.ts"],"sourcesContent":["/**\n * \"Store this only with consent\" — the helper every integrator ends up writing.\n *\n * A first-party cookie of your own (an A/B bucket, an affiliate id, a chat session) is\n * only lawful while the visitor consents to the category it belongs to. `consentCookie`\n * writes it the moment that consent holds and removes it the moment it stops — a\n * withdrawal from a footer link, a \"Deny all\", a selection that unticks the category —\n * and does nothing at all until the embed has said what the visitor decided.\n *\n * Framework-free: it listens to the embed's `CookieMunchOnChange` window event, so it\n * works with or without `<ConsentProvider>`, and with custom categories.\n */\n\n/** Anything carrying a category decision: the public `consent` snapshot or a `ConsentState`. */\ntype ConsentLike = Record<string, unknown> & { custom?: Record<string, unknown> };\n\n/**\n * Whether `category` is granted in a consent snapshot. `necessary` is always granted. A\n * custom category is read from the top level (the public `CookieMunch.consent` snapshot)\n * or from `custom` (the `ConsentState` that events carry). Anything else: not granted.\n */\nexport function isGranted(consent: ConsentLike | null | undefined, category: string): boolean {\n if (category === 'necessary') return true;\n if (!consent) return false;\n const top = consent[category];\n if (typeof top === 'boolean') return top;\n return consent.custom?.[category] === true;\n}\n\nexport interface ConsentCookieOptions {\n /** Lifetime in days. Default: a session cookie (no max-age). */\n maxAgeDays?: number;\n /** Default `/`. */\n path?: string;\n /** Domain attribute, e.g. `example.com` to share across subdomains. Default: host-only. */\n domain?: string;\n /** Default `Lax`. */\n sameSite?: 'Lax' | 'Strict' | 'None';\n /** Default: true on an https page. Forced on with `sameSite: 'None'`, as browsers require. */\n secure?: boolean;\n}\n\n/** The detail of `CookieMunchOnChange` — only the part this helper reads. */\ninterface ChangeDetail {\n consent?: ConsentLike;\n}\n\nfunction hasDom(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\nfunction attributes(opts: ConsentCookieOptions): string[] {\n const parts = [`path=${opts.path ?? '/'}`];\n if (opts.domain) parts.push(`domain=${opts.domain}`);\n const sameSite = opts.sameSite ?? 'Lax';\n parts.push(`SameSite=${sameSite}`);\n const secure = opts.secure ?? (sameSite === 'None' || window.location?.protocol === 'https:');\n if (secure || sameSite === 'None') parts.push('Secure');\n return parts;\n}\n\nfunction setCookie(name: string, value: string, opts: ConsentCookieOptions): void {\n const parts = [`${name}=${encodeURIComponent(value)}`, ...attributes(opts)];\n if (typeof opts.maxAgeDays === 'number' && opts.maxAgeDays > 0) {\n parts.push(`max-age=${Math.round(opts.maxAgeDays * 86400)}`);\n }\n document.cookie = parts.join('; ');\n}\n\nfunction hasCookie(name: string): boolean {\n return document.cookie.split(';').some((c) => c.trim().startsWith(`${name}=`));\n}\n\n/** Delete with the same path and domain it was written with — a browser matches on all three. */\nfunction removeCookie(name: string, opts: ConsentCookieOptions): void {\n document.cookie = [`${name}=`, ...attributes(opts), 'max-age=0', 'expires=Thu, 01 Jan 1970 00:00:00 GMT'].join('; ');\n}\n\n/**\n * Keep the cookie `name` in step with consent for `category`: written (with `value`) while\n * it is granted, removed when it is not. `value` may be a function, called only when the\n * cookie is about to be written and is not already there — so an id is never even\n * generated without consent, and a stored one survives page loads.\n *\n * Applies the current decision immediately when the embed has already loaded, then follows\n * every change. Until the embed reports a decision, nothing is written or removed. Returns\n * a function that stops following (the cookie is left as it is).\n *\n * const stop = consentCookie('ab_bucket', 'statistics', () => pickBucket(), { maxAgeDays: 30 });\n */\nexport function consentCookie(\n name: string,\n category: string,\n value: string | (() => string),\n opts: ConsentCookieOptions = {},\n): () => void {\n if (!hasDom()) return () => {};\n\n let written: boolean | null = null;\n const apply = (consent: ConsentLike | null | undefined) => {\n if (!consent) return;\n const granted = isGranted(consent, category);\n if (granted) {\n // Once per grant, not on every repeated announcement. A lazy value that is already\n // stored (from an earlier page) is kept: regenerating it would, say, move a visitor\n // to a new A/B bucket on every page load.\n if (written !== true) {\n if (typeof value !== 'function') setCookie(name, value, opts);\n else if (!hasCookie(name)) setCookie(name, value(), opts);\n }\n } else {\n removeCookie(name, opts);\n }\n written = granted;\n };\n\n const onChange = (e: Event) => apply((e as CustomEvent<ChangeDetail>).detail?.consent);\n window.addEventListener('CookieMunchOnChange', onChange);\n\n // Already loaded: apply what is in force now. (A later load announces itself, including\n // a returning visitor's stored decision, through the same event.)\n const api = (window as { CookieMunch?: { consent?: unknown } }).CookieMunch;\n if (api?.consent) apply(api.consent as ConsentLike);\n\n return () => window.removeEventListener('CookieMunchOnChange', onChange);\n}\n","// Consent outside React: gate code on it, or hear about it, without writing a wrapper round the window event.\nimport { isGranted } from './consent-cookie.js';\n\ntype Consent = Record<string, unknown> & { custom?: Record<string, boolean> };\n\n/** The visitor's decision, once the embed has one. A later load announces itself through the change event. */\nfunction decided(): Consent | null {\n const cm = window.CookieMunch;\n return cm?.hasResponse ? (cm.consent as unknown as Consent) : null;\n}\n\n/** Whether `category` is granted now. False on the server and before a decision; `necessary` is always true. */\nexport function hasConsent(category: string): boolean {\n if (category === 'necessary') return true;\n return typeof window !== 'undefined' && isGranted(decided() as never, category);\n}\n\n/**\n * Calls `fn` with the consent on every decision, and once straight away when the visitor has already decided.\n * Returns the unsubscribe. Does nothing on the server.\n */\nexport function onConsentChange(fn: (consent: Consent) => void): () => void {\n if (typeof window === 'undefined') return () => {};\n let active = true;\n const onChange = (e: Event) => {\n const consent = (e as CustomEvent<{ consent?: Consent }>).detail?.consent;\n if (consent && active) fn(consent);\n };\n window.addEventListener('CookieMunchOnChange', onChange);\n const already = decided();\n if (already) queueMicrotask(() => { if (active) fn(already); });\n return () => {\n active = false;\n window.removeEventListener('CookieMunchOnChange', onChange);\n };\n}\n","/**\n * Read the embed's consent cookie on the server, where `document` does not exist — a Server\n * Component, a route handler, middleware:\n *\n * const consent = parseConsentCookie((await cookies()).get(CONSENT_COOKIE_NAME)?.value);\n * if (isGranted(consent, 'statistics')) { ... }\n *\n * The wire format is the embed's: URL-encoded JSON of its consent state. A legacy Cookiebot\n * `CookieConsent` value (a relaxed JS object literal) is read too. Standalone on purpose — this\n * package never imports `@cookiemunch/core`.\n */\n\n/** The first-party cookie the embed stores the visitor's decision in. */\nexport const CONSENT_COOKIE_NAME = 'CookieMunch';\n\n/** The category decisions a consent cookie carries. Pass it to `isGranted`. */\nexport interface ConsentCookieState {\n necessary: true;\n preferences: boolean;\n statistics: boolean;\n marketing: boolean;\n /** Custom categories the site defines, by id. */\n custom?: Record<string, boolean>;\n [key: string]: unknown;\n}\n\nfunction decode(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n}\n\nfunction json(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/** `{stamp:'abc==',necessary:true,...}` → strict JSON: single quotes doubled, bare keys quoted. */\nfunction legacy(text: string): unknown {\n if (!text.includes('necessary')) return undefined;\n return json(text.replace(/'/g, '\"').replace(/([{,]\\s*)([A-Za-z_]\\w*)\\s*:/g, '$1\"$2\":'));\n}\n\n/**\n * The decisions in a consent cookie value, or `null` when there is none the embed would honour\n * (not its format, or a required field missing or mistyped). `necessary` is always\n * true, whatever the cookie says. `null` passed to `isGranted` grants only `necessary`.\n */\nexport function parseConsentCookie(raw: string | null | undefined): ConsentCookieState | null {\n if (!raw) return null;\n const text = decode(raw);\n const o = json(text) ?? legacy(text);\n if (o === null || typeof o !== 'object' || Array.isArray(o)) return null;\n const r = o as Record<string, unknown>;\n const { preferences, statistics, marketing } = r;\n if (typeof preferences !== 'boolean' || typeof statistics !== 'boolean' || typeof marketing !== 'boolean') return null;\n // The rest of what the embed requires before it honours a value (see /docs/consent-cookie).\n if (r.method !== 'explicit' && r.method !== 'implied') return null;\n if (typeof r.ver !== 'number' || typeof r.utc !== 'number' || typeof r.region !== 'string') return null;\n if (typeof r.stamp !== 'string' && typeof r.stamp !== 'number') return null;\n const state: ConsentCookieState = { necessary: true, preferences, statistics, marketing };\n if (r.custom !== null && typeof r.custom === 'object' && !Array.isArray(r.custom)) {\n const custom: Record<string, boolean> = {};\n for (const [k, v] of Object.entries(r.custom as Record<string, unknown>)) if (typeof v === 'boolean') custom[k] = v;\n if (Object.keys(custom).length > 0) state.custom = custom;\n }\n return state;\n}\n","// The server-safe half: no directive, nothing from React. Callable from a Server Component —\n// read the consent cookie from `cookies()` and decide what to render before any client code runs.\nexport { consentCookie, isGranted, type ConsentCookieOptions } from './consent-cookie.js';\nexport { hasConsent, onConsentChange } from './consent-helpers.js';\nexport { CONSENT_COOKIE_NAME, parseConsentCookie, type ConsentCookieState } from './consent-parse.js';\nexport type { Category, CategoryId, CookieMunchCategories, PublicConsent, CookieMunchGlobal } from './types.js';\n\n/**\n * The URL shapes a minted link can have (docs: account-linked-rights): `https://<customDomain>/?t=…`\n * when the site has an active custom rights domain, else `https://<app>/r/<cbid>?t=…`. Anything\n * else — another scheme, no token — is refused rather than followed.\n */\nexport function isRightsLinkUrl(url: string, customDomain?: string | null): boolean {\n let u: URL;\n try {\n u = new URL(url);\n } catch {\n return false;\n }\n if (u.protocol !== 'https:' || !u.searchParams.get('t')) return false;\n if (customDomain) return u.host === customDomain && u.pathname === '/';\n return /^\\/r\\/[^/]+$/.test(u.pathname);\n}\n"],"mappings":";AAqBO,SAAS,UAAU,SAAyC,UAA2B;AAC5F,MAAI,aAAa,YAAa,QAAO;AACrC,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,MAAM,QAAQ,QAAQ;AAC5B,MAAI,OAAO,QAAQ,UAAW,QAAO;AACrC,SAAO,QAAQ,SAAS,QAAQ,MAAM;AACxC;AAoBA,SAAS,SAAkB;AACzB,SAAO,OAAO,WAAW,eAAe,OAAO,aAAa;AAC9D;AAEA,SAAS,WAAW,MAAsC;AACxD,QAAM,QAAQ,CAAC,QAAQ,KAAK,QAAQ,GAAG,EAAE;AACzC,MAAI,KAAK,OAAQ,OAAM,KAAK,UAAU,KAAK,MAAM,EAAE;AACnD,QAAM,WAAW,KAAK,YAAY;AAClC,QAAM,KAAK,YAAY,QAAQ,EAAE;AACjC,QAAM,SAAS,KAAK,WAAW,aAAa,UAAU,OAAO,UAAU,aAAa;AACpF,MAAI,UAAU,aAAa,OAAQ,OAAM,KAAK,QAAQ;AACtD,SAAO;AACT;AAEA,SAAS,UAAU,MAAc,OAAe,MAAkC;AAChF,QAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,mBAAmB,KAAK,CAAC,IAAI,GAAG,WAAW,IAAI,CAAC;AAC1E,MAAI,OAAO,KAAK,eAAe,YAAY,KAAK,aAAa,GAAG;AAC9D,UAAM,KAAK,WAAW,KAAK,MAAM,KAAK,aAAa,KAAK,C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W,UAAW,QAAO;AAC9D,MAAI,OAAO,EAAE,QAAQ,YAAY,OAAO,EAAE,QAAQ,YAAY,OAAO,EAAE,WAAW,SAAU,QAAO;AACnG,MAAI,OAAO,EAAE,UAAU,YAAY,OAAO,EAAE,UAAU,SAAU,QAAO;AACvE,QAAM,QAA4B,EAAE,WAAW,MAAM,aAAa,YAAY,UAAU;AACxF,MAAI,EAAE,WAAW,QAAQ,OAAO,EAAE,WAAW,YAAY,CAAC,MAAM,QAAQ,EAAE,MAAM,GAAG;AACjF,UAAM,SAAkC,CAAC;AACzC,eAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,EAAE,MAAiC,EAAG,KAAI,OAAO,MAAM,UAAW,QAAO,CAAC,IAAI;AAClH,QAAI,OAAO,KAAK,MAAM,EAAE,SAAS,EAAG,OAAM,SAAS;AAAA,EACrD;AACA,SAAO;AACT;;;AC5DO,SAAS,gBAAgB,KAAa,cAAuC;AAClF,MAAI;AACJ,MAAI;AACF,QAAI,IAAI,IAAI,GAAG;AAAA,EACjB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,EAAE,aAAa,YAAY,CAAC,EAAE,aAAa,IAAI,GAAG,EAAG,QAAO;AAChE,MAAI,aAAc,QAAO,EAAE,SAAS,gBAAgB,EAAE,aAAa;AACnE,SAAO,eAAe,KAAK,EAAE,QAAQ;AACvC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/consent-cookie.ts","../src/consent-helpers.ts","../src/consent-parse.ts","../src/helpers.ts"],"sourcesContent":["/**\n * \"Store this only with consent\" — the helper every integrator ends up writing.\n *\n * A first-party cookie of your own (an A/B bucket, an affiliate id, a chat session) is\n * only lawful while the visitor consents to the category it belongs to. `consentCookie`\n * writes it the moment that consent holds and removes it the moment it stops — a\n * withdrawal from a footer link, a \"Deny all\", a selection that unticks the category —\n * and does nothing at all until the embed has said what the visitor decided.\n *\n * Framework-free: it listens to the embed's `CookieMunchOnChange` window event, so it\n * works with or without `<ConsentProvider>`, and with custom categories.\n */\n\n/** Anything carrying a category decision: the public `consent` snapshot or a `ConsentState`. */\ntype ConsentLike = Record<string, unknown> & { custom?: Record<string, unknown> };\n\n/**\n * Whether `category` is granted in a consent snapshot. `necessary` is always granted. A\n * custom category is read from the top level (the public `CookieMunch.consent` snapshot)\n * or from `custom` (the `ConsentState` that events carry). Anything else: not granted.\n */\nexport function isGranted(consent: ConsentLike | null | undefined, category: string): boolean {\n if (category === 'necessary') return true;\n if (!consent) return false;\n const top = consent[category];\n if (typeof top === 'boolean') return top;\n return consent.custom?.[category] === true;\n}\n\nexport interface ConsentCookieOptions {\n /** Lifetime in days. Default: a session cookie (no max-age). */\n maxAgeDays?: number;\n /** Default `/`. */\n path?: string;\n /** Domain attribute, e.g. `example.com` to share across subdomains. Default: host-only. */\n domain?: string;\n /** Default `Lax`. */\n sameSite?: 'Lax' | 'Strict' | 'None';\n /** Default: true on an https page. Forced on with `sameSite: 'None'`, as browsers require. */\n secure?: boolean;\n}\n\n/** The detail of `CookieMunchOnChange` — only the part this helper reads. */\ninterface ChangeDetail {\n consent?: ConsentLike;\n}\n\nfunction hasDom(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\nfunction attributes(opts: ConsentCookieOptions): string[] {\n const parts = [`path=${opts.path ?? '/'}`];\n if (opts.domain) parts.push(`domain=${opts.domain}`);\n const sameSite = opts.sameSite ?? 'Lax';\n parts.push(`SameSite=${sameSite}`);\n const secure = opts.secure ?? (sameSite === 'None' || window.location?.protocol === 'https:');\n if (secure || sameSite === 'None') parts.push('Secure');\n return parts;\n}\n\nfunction setCookie(name: string, value: string, opts: ConsentCookieOptions): void {\n const parts = [`${name}=${encodeURIComponent(value)}`, ...attributes(opts)];\n if (typeof opts.maxAgeDays === 'number' && opts.maxAgeDays > 0) {\n parts.push(`max-age=${Math.round(opts.maxAgeDays * 86400)}`);\n }\n document.cookie = parts.join('; ');\n}\n\nfunction hasCookie(name: string): boolean {\n return document.cookie.split(';').some((c) => c.trim().startsWith(`${name}=`));\n}\n\n/** Delete with the same path and domain it was written with — a browser matches on all three. */\nfunction removeCookie(name: string, opts: ConsentCookieOptions): void {\n document.cookie = [`${name}=`, ...attributes(opts), 'max-age=0', 'expires=Thu, 01 Jan 1970 00:00:00 GMT'].join('; ');\n}\n\n/**\n * Keep the cookie `name` in step with consent for `category`: written (with `value`) while\n * it is granted, removed when it is not. `value` may be a function, called only when the\n * cookie is about to be written and is not already there — so an id is never even\n * generated without consent, and a stored one survives page loads.\n *\n * Applies the current decision immediately when the embed has already loaded, then follows\n * every change. Until the embed reports a decision, nothing is written or removed. Returns\n * a function that stops following (the cookie is left as it is).\n *\n * const stop = consentCookie('ab_bucket', 'statistics', () => pickBucket(), { maxAgeDays: 30 });\n */\nexport function consentCookie(\n name: string,\n category: string,\n value: string | (() => string),\n opts: ConsentCookieOptions = {},\n): () => void {\n if (!hasDom()) return () => {};\n\n let written: boolean | null = null;\n const apply = (consent: ConsentLike | null | undefined) => {\n if (!consent) return;\n const granted = isGranted(consent, category);\n if (granted) {\n // Once per grant, not on every repeated announcement. A lazy value that is already\n // stored (from an earlier page) is kept: regenerating it would, say, move a visitor\n // to a new A/B bucket on every page load.\n if (written !== true) {\n if (typeof value !== 'function') setCookie(name, value, opts);\n else if (!hasCookie(name)) setCookie(name, value(), opts);\n }\n } else {\n removeCookie(name, opts);\n }\n written = granted;\n };\n\n const onChange = (e: Event) => apply((e as CustomEvent<ChangeDetail>).detail?.consent);\n window.addEventListener('CookieMunchOnChange', onChange);\n\n // Already loaded: apply what is in force now. (A later load announces itself, including\n // a returning visitor's stored decision, through the same event.)\n const api = (window as { CookieMunch?: { consent?: unknown } }).CookieMunch;\n if (api?.consent) apply(api.consent as ConsentLike);\n\n return () => window.removeEventListener('CookieMunchOnChange', onChange);\n}\n","// Consent outside React: gate code on it, or hear about it, without writing a wrapper round the window event.\nimport { isGranted } from './consent-cookie.js';\n\ntype Consent = Record<string, unknown> & { custom?: Record<string, boolean> };\n\n/** The visitor's decision, once the embed has one. A later load announces itself through the change event. */\nfunction decided(): Consent | null {\n const cm = window.CookieMunch;\n return cm?.hasResponse ? (cm.consent as unknown as Consent) : null;\n}\n\n/** Whether `category` is granted now. False on the server and before a decision; `necessary` is always true. */\nexport function hasConsent(category: string): boolean {\n if (category === 'necessary') return true;\n return typeof window !== 'undefined' && isGranted(decided() as never, category);\n}\n\n/**\n * Calls `fn` with the consent on every decision, and once straight away when the visitor has already decided.\n * Returns the unsubscribe. Does nothing on the server.\n */\nexport function onConsentChange(fn: (consent: Consent) => void): () => void {\n if (typeof window === 'undefined') return () => {};\n let active = true;\n const onChange = (e: Event) => {\n const consent = (e as CustomEvent<{ consent?: Consent }>).detail?.consent;\n if (consent && active) fn(consent);\n };\n window.addEventListener('CookieMunchOnChange', onChange);\n const already = decided();\n if (already) queueMicrotask(() => { if (active) fn(already); });\n return () => {\n active = false;\n window.removeEventListener('CookieMunchOnChange', onChange);\n };\n}\n\n/** What `onConsentCategory` hands its callback. */\nexport interface ConsentTransition {\n /** The category's state now. */\n granted: boolean;\n /** Its state before this call: undefined on the first call (no decision seen yet in this page). */\n previous: boolean | undefined;\n /** True for the first call when the visitor had already decided before you subscribed: start what was granted, nothing changed. */\n replay: boolean;\n /** Why it changed, as the embed's change event says (`banner`, `api`, `withdraw`…); `replay` for a replay. */\n cause: string;\n}\n\n/**\n * Calls `fn` only when `category` actually changes: once straight away as a replay when the visitor\n * has already decided, then on each grant or withdrawal, never twice for the same state. Start a\n * vendor on `granted`, stop it when `!granted && previous`. Returns the unsubscribe; nothing on the server.\n */\nexport function onConsentCategory(category: string, fn: (t: ConsentTransition) => void): () => void {\n if (typeof window === 'undefined') return () => {};\n let active = true;\n let last: boolean | undefined;\n const emit = (consent: Consent, cause: string, replay: boolean) => {\n const granted = category === 'necessary' || isGranted(consent as never, category);\n if (!active || granted === last) return;\n const previous = last;\n last = granted;\n fn({ granted, previous, replay, cause });\n };\n const onChange = (e: Event) => {\n const d = (e as CustomEvent<{ consent?: Consent; cause?: unknown }>).detail;\n if (d?.consent) emit(d.consent, typeof d.cause === 'string' ? d.cause : 'change', false);\n };\n window.addEventListener('CookieMunchOnChange', onChange);\n const already = decided();\n if (already) queueMicrotask(() => emit(already, 'replay', true));\n return () => {\n active = false;\n window.removeEventListener('CookieMunchOnChange', onChange);\n };\n}\n","/**\n * Read the embed's consent cookie on the server, where `document` does not exist — a Server\n * Component, a route handler, middleware:\n *\n * const consent = parseConsentCookie((await cookies()).get(CONSENT_COOKIE_NAME)?.value);\n * if (isGranted(consent, 'statistics')) { ... }\n *\n * The wire format is the embed's: URL-encoded JSON of its consent state. A legacy Cookiebot\n * `CookieConsent` value (a relaxed JS object literal) is read too. Standalone on purpose — this\n * package never imports `@cookiemunch/core`.\n */\n\n/** The first-party cookie the embed stores the visitor's decision in. */\nexport const CONSENT_COOKIE_NAME = 'CookieMunch';\n\n/** The category decisions a consent cookie carries. Pass it to `isGranted`. */\nexport interface ConsentCookieState {\n necessary: true;\n preferences: boolean;\n statistics: boolean;\n marketing: boolean;\n /** Custom categories the site defines, by id. */\n custom?: Record<string, boolean>;\n [key: string]: unknown;\n}\n\nfunction decode(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n}\n\nfunction json(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/** `{stamp:'abc==',necessary:true,...}` → strict JSON: single quotes doubled, bare keys quoted. */\nfunction legacy(text: string): unknown {\n if (!text.includes('necessary')) return undefined;\n return json(text.replace(/'/g, '\"').replace(/([{,]\\s*)([A-Za-z_]\\w*)\\s*:/g, '$1\"$2\":'));\n}\n\n/**\n * The decisions in a consent cookie value, or `null` when there is none the embed would honour\n * (not its format, or a required field missing or mistyped). `necessary` is always\n * true, whatever the cookie says. `null` passed to `isGranted` grants only `necessary`.\n */\nexport function parseConsentCookie(raw: string | null | undefined): ConsentCookieState | null {\n if (!raw) return null;\n const text = decode(raw);\n const o = json(text) ?? legacy(text);\n if (o === null || typeof o !== 'object' || Array.isArray(o)) return null;\n const r = o as Record<string, unknown>;\n const { preferences, statistics, marketing } = r;\n if (typeof preferences !== 'boolean' || typeof statistics !== 'boolean' || typeof marketing !== 'boolean') return null;\n // The rest of what the embed requires before it honours a value (see /docs/consent-cookie).\n if (r.method !== 'explicit' && r.method !== 'implied') return null;\n if (typeof r.ver !== 'number' || typeof r.utc !== 'number' || typeof r.region !== 'string') return null;\n if (typeof r.stamp !== 'string' && typeof r.stamp !== 'number') return null;\n const state: ConsentCookieState = { necessary: true, preferences, statistics, marketing };\n if (r.custom !== null && typeof r.custom === 'object' && !Array.isArray(r.custom)) {\n const custom: Record<string, boolean> = {};\n for (const [k, v] of Object.entries(r.custom as Record<string, unknown>)) if (typeof v === 'boolean') custom[k] = v;\n if (Object.keys(custom).length > 0) state.custom = custom;\n }\n return state;\n}\n","// The server-safe half: no directive, nothing from React. Callable from a Server Component —\n// read the consent cookie from `cookies()` and decide what to render before any client code runs.\nexport { consentCookie, isGranted, type ConsentCookieOptions } from './consent-cookie.js';\nexport { hasConsent, onConsentChange, onConsentCategory, type ConsentTransition } from './consent-helpers.js';\nexport { CONSENT_COOKIE_NAME, parseConsentCookie, type ConsentCookieState } from './consent-parse.js';\nexport type { Category, CategoryId, CookieMunchCategories, PublicConsent, CookieMunchGlobal } from './types.js';\n\n/**\n * The URL shapes a minted link can have (docs: account-linked-rights): `https://<customDomain>/?t=…`\n * when the site has an active custom rights domain, else `https://<app>/r/<cbid>?t=…`. Anything\n * else — another scheme, no token — is refused rather than followed.\n */\nexport function isRightsLinkUrl(url: string, customDomain?: string | null): boolean {\n let u: URL;\n try {\n u = new URL(url);\n } catch {\n return false;\n }\n if (u.protocol !== 'https:' || !u.searchParams.get('t')) return false;\n if (customDomain) return u.host === customDomain && u.pathname === '/';\n return /^\\/r\\/[^/]+$/.test(u.pathname);\n}\n"],"mappings":";AAqBO,SAAS,UAAU,SAAyC,UAA2B;AAC5F,MAAI,aAAa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ConsentProvider, ConsentProviderProps, CookieDeclaration, CookieDeclarationProps, CookieSettingsLink, CookieSettingsLinkProps, MintedRightsLink, RightsLink, RightsLinkProps, useBannerInset, useConsent, useConsentCookie, useConsentValue } from './client.js';
|
|
2
|
-
export { CONSENT_COOKIE_NAME, Category, CategoryId, ConsentCookieOptions, ConsentCookieState, CookieMunchCategories, CookieMunchGlobal, PublicConsent, consentCookie, hasConsent, isGranted, isRightsLinkUrl, onConsentChange, parseConsentCookie } from './helpers.js';
|
|
1
|
+
export { ConsentContextValue, ConsentGate, ConsentGateProps, ConsentIdentity, ConsentIdentityProps, ConsentProvider, ConsentProviderProps, CookieDeclaration, CookieDeclarationProps, CookieSettingsLink, CookieSettingsLinkProps, MintedRightsLink, RightsLink, RightsLinkProps, useBannerInset, useConsent, useConsentCookie, useConsentTransition, useConsentValue } from './client.js';
|
|
2
|
+
export { CONSENT_COOKIE_NAME, Category, CategoryId, ConsentCookieOptions, ConsentCookieState, ConsentTransition, CookieMunchCategories, CookieMunchGlobal, PublicConsent, consentCookie, hasConsent, isGranted, isRightsLinkUrl, onConsentCategory, onConsentChange, parseConsentCookie } from './helpers.js';
|
package/dist/index.js
CHANGED
|
@@ -6,13 +6,16 @@ import {
|
|
|
6
6
|
useConsentValue,
|
|
7
7
|
useConsentCookie,
|
|
8
8
|
useBannerInset,
|
|
9
|
+
useConsentTransition,
|
|
9
10
|
RightsLink,
|
|
10
11
|
CookieDeclaration,
|
|
11
|
-
CookieSettingsLink
|
|
12
|
+
CookieSettingsLink,
|
|
13
|
+
ConsentIdentity
|
|
12
14
|
} from "./client.js";
|
|
13
15
|
import {
|
|
14
16
|
hasConsent,
|
|
15
17
|
onConsentChange,
|
|
18
|
+
onConsentCategory,
|
|
16
19
|
consentCookie,
|
|
17
20
|
isGranted,
|
|
18
21
|
CONSENT_COOKIE_NAME,
|
|
@@ -22,6 +25,7 @@ import {
|
|
|
22
25
|
export {
|
|
23
26
|
CONSENT_COOKIE_NAME,
|
|
24
27
|
ConsentGate,
|
|
28
|
+
ConsentIdentity,
|
|
25
29
|
ConsentProvider,
|
|
26
30
|
CookieDeclaration,
|
|
27
31
|
CookieSettingsLink,
|
|
@@ -30,11 +34,13 @@ export {
|
|
|
30
34
|
hasConsent,
|
|
31
35
|
isGranted,
|
|
32
36
|
isRightsLinkUrl,
|
|
37
|
+
onConsentCategory,
|
|
33
38
|
onConsentChange,
|
|
34
39
|
parseConsentCookie,
|
|
35
40
|
useBannerInset,
|
|
36
41
|
useConsent,
|
|
37
42
|
useConsentCookie,
|
|
43
|
+
useConsentTransition,
|
|
38
44
|
useConsentValue
|
|
39
45
|
};
|
|
40
46
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// No directive here, only re-exports. On the React Server layer Next turns the client.js names\n// into client references and leaves the helpers as plain functions, so one root import —\n// `import { ConsentProvider, isGranted } from '@cookiemunch/react'` — works in a Server Component.\nexport {\n ConsentProvider,\n type ConsentProviderProps,\n useConsent,\n type ConsentContextValue,\n ConsentGate,\n type ConsentGateProps,\n useConsentValue,\n useConsentCookie,\n useBannerInset,\n RightsLink,\n type RightsLinkProps,\n type MintedRightsLink,\n CookieDeclaration,\n type CookieDeclarationProps,\n CookieSettingsLink,\n type CookieSettingsLinkProps,\n} from './client.js';\nexport {\n hasConsent,\n onConsentChange,\n consentCookie,\n isGranted,\n type ConsentCookieOptions,\n CONSENT_COOKIE_NAME,\n parseConsentCookie,\n isRightsLinkUrl,\n type ConsentCookieState,\n type Category,\n type CategoryId,\n type CookieMunchCategories,\n type PublicConsent,\n type CookieMunchGlobal,\n} from './helpers.js';\n"],"mappings":";AAGA;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EAEA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// No directive here, only re-exports. On the React Server layer Next turns the client.js names\n// into client references and leaves the helpers as plain functions, so one root import —\n// `import { ConsentProvider, isGranted } from '@cookiemunch/react'` — works in a Server Component.\nexport {\n ConsentProvider,\n type ConsentProviderProps,\n useConsent,\n type ConsentContextValue,\n ConsentGate,\n type ConsentGateProps,\n useConsentValue,\n useConsentCookie,\n useBannerInset,\n useConsentTransition,\n RightsLink,\n type RightsLinkProps,\n type MintedRightsLink,\n CookieDeclaration,\n type CookieDeclarationProps,\n CookieSettingsLink,\n type CookieSettingsLinkProps,\n ConsentIdentity,\n type ConsentIdentityProps,\n} from './client.js';\nexport {\n hasConsent,\n onConsentChange,\n onConsentCategory,\n type ConsentTransition,\n consentCookie,\n isGranted,\n type ConsentCookieOptions,\n CONSENT_COOKIE_NAME,\n parseConsentCookie,\n isRightsLinkUrl,\n type ConsentCookieState,\n type Category,\n type CategoryId,\n type CookieMunchCategories,\n type PublicConsent,\n type CookieMunchGlobal,\n} from './helpers.js';\n"],"mappings":";AAGA;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EAEA;AAAA,EAEA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;","names":[]}
|