@cookiemunch/react 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -67,4 +67,52 @@ declare function useConsentValue(category: string): boolean;
67
67
  */
68
68
  declare function useConsentCookie(name: string, category: string, value: string | (() => string), opts?: ConsentCookieOptions): void;
69
69
 
70
- export { type ConsentContextValue, ConsentGate, type ConsentGateProps, ConsentProvider, type ConsentProviderProps, useConsent, useConsentCookie, useConsentValue };
70
+ /** What `mint` may resolve to: the mint response from `POST /v1/sites/{cbid}/rights-links`, or just its `url`. */
71
+ type MintedRightsLink = string | {
72
+ url: string;
73
+ customDomain?: string | null;
74
+ };
75
+ interface RightsLinkProps {
76
+ /**
77
+ * Mints a single-use account link for the signed-in person — a server action (or an endpoint
78
+ * you call) that holds a `dsar:rights-links` key and calls `POST /v1/sites/{cbid}/rights-links`.
79
+ * Never put the key in the browser. Called on click, not on render: links are single-use and
80
+ * expire (15 minutes by default), so one minted per page view would mostly go to waste.
81
+ */
82
+ mint: () => Promise<MintedRightsLink>;
83
+ /** 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>`. */
84
+ fallbackHref?: string;
85
+ children?: ReactNode;
86
+ className?: string;
87
+ /** Called when a mint fails or returns a URL that is not a rights link, before falling back. */
88
+ onError?: (error: Error) => void;
89
+ }
90
+ /**
91
+ * "Your privacy rights" for a signed-in person: on click it mints an account link (their email is
92
+ * filled in and locked, the email-code step skipped) and opens it. Plain anchor markup, so it
93
+ * renders the same on the server and the client.
94
+ */
95
+ declare function RightsLink({ mint, fallbackHref, children, className, onError }: RightsLinkProps): react.JSX.Element;
96
+
97
+ interface CookieDeclarationProps {
98
+ /** Shown when the site has no cookies to list yet (the mount's `data-empty`). */
99
+ emptyText?: string;
100
+ className?: string;
101
+ id?: string;
102
+ }
103
+ /**
104
+ * The live cookie declaration, for a privacy page in a React / Next.js app (CKM-S-10).
105
+ *
106
+ * Renders `<div data-cc="declaration">` and lets the embed draw the table into it. The
107
+ * embed fills the element whenever it appears — on first load, after a client-side
108
+ * navigation, or before hydration on a server-rendered page — so the element's children
109
+ * belong to the embed, not to React:
110
+ * - `dangerouslySetInnerHTML` with a constant empty string tells React it does not own
111
+ * the children, so it neither hydrates nor replaces them;
112
+ * - `suppressHydrationWarning` covers the one difference React would otherwise report:
113
+ * the server sent an empty element and the embed may already have filled it.
114
+ * After mount it asks the embed to draw this element, in case it was added after load.
115
+ */
116
+ declare function CookieDeclaration({ emptyText, className, id }: CookieDeclarationProps): react.JSX.Element;
117
+
118
+ export { type ConsentContextValue, ConsentGate, type ConsentGateProps, ConsentProvider, type ConsentProviderProps, CookieDeclaration, type CookieDeclarationProps, type MintedRightsLink, RightsLink, type RightsLinkProps, useConsent, useConsentCookie, useConsentValue };
package/dist/client.js CHANGED
@@ -143,9 +143,67 @@ function useConsentCookie(name, category, value, opts = {}) {
143
143
  [name, category, value, maxAgeDays, path, domain, sameSite, secure]
144
144
  );
145
145
  }
146
+
147
+ // src/RightsLink.tsx
148
+ import { useCallback, useState as useState2 } from "react";
149
+ import { isRightsLinkUrl } from "./helpers.js";
150
+ import { jsx as jsx3 } from "react/jsx-runtime";
151
+ function RightsLink({ mint, fallbackHref, children = "Your privacy rights", className, onError }) {
152
+ const [busy, setBusy] = useState2(false);
153
+ const onClick = useCallback(
154
+ async (e) => {
155
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
156
+ e.preventDefault();
157
+ if (busy) return;
158
+ setBusy(true);
159
+ try {
160
+ const got = await mint();
161
+ const url = typeof got === "string" ? got : got.url;
162
+ const customDomain = typeof got === "string" ? void 0 : got.customDomain;
163
+ if (!isRightsLinkUrl(url, customDomain)) throw new Error(`not a rights link: ${url}`);
164
+ window.location.assign(url);
165
+ } catch (err) {
166
+ onError?.(err instanceof Error ? err : new Error(String(err)));
167
+ if (fallbackHref) window.location.assign(fallbackHref);
168
+ } finally {
169
+ setBusy(false);
170
+ }
171
+ },
172
+ [busy, mint, fallbackHref, onError]
173
+ );
174
+ return /* @__PURE__ */ jsx3("a", { href: fallbackHref ?? "#", className, onClick, "aria-busy": busy || void 0, children });
175
+ }
176
+
177
+ // src/CookieDeclaration.tsx
178
+ import { useEffect as useEffect3, useRef as useRef2 } from "react";
179
+ import { jsx as jsx4 } from "react/jsx-runtime";
180
+ var EMPTY = { __html: "" };
181
+ function CookieDeclaration({ emptyText, className, id }) {
182
+ const ref = useRef2(null);
183
+ useEffect3(() => {
184
+ const el = ref.current;
185
+ const api = typeof window !== "undefined" ? window.CookieMunch : void 0;
186
+ if (el && !el.hasChildNodes()) void api?.renderDeclaration?.(el)?.catch?.(() => {
187
+ });
188
+ }, []);
189
+ return /* @__PURE__ */ jsx4(
190
+ "div",
191
+ {
192
+ ref,
193
+ id,
194
+ className,
195
+ "data-cc": "declaration",
196
+ ...emptyText !== void 0 ? { "data-empty": emptyText } : {},
197
+ suppressHydrationWarning: true,
198
+ dangerouslySetInnerHTML: EMPTY
199
+ }
200
+ );
201
+ }
146
202
  export {
147
203
  ConsentGate,
148
204
  ConsentProvider,
205
+ CookieDeclaration,
206
+ RightsLink,
149
207
  useConsent,
150
208
  useConsentCookie,
151
209
  useConsentValue
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ConsentProvider.tsx","../src/context.ts","../src/useConsent.ts","../src/ConsentGate.tsx","../src/useConsentValue.ts"],"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 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: string): 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: string,\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"],"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,SAAmC;AACvF,QAAM,WAAW,SAAS,eAAe,SAAS;AAClD,MAAI,SAAU;AACd,QAAM,SAAS,SAAS,cAAc,QAAQ;AAC9C,SAAO,KAAK;AACZ,SAAO,QAAQ;AACf,SAAO,MAAM;AACb,SAAO,aAAa,aAAa,IAAI;AACrC,MAAI,QAAS,QAAO,aAAa,YAAY,OAAO;AACpD,GAAC,SAAS,QAAQ,SAAS,iBAAiB,YAAY,MAAM;AAChE;AAWO,SAAS,gBAAgB,EAAE,MAAM,MAAM,aAAa,SAAS,SAAS,GAAyB;AACpG,QAAM,SAAS,OAAiC,IAAI;AACpD,QAAM,CAAC,MAAM,OAAO,IAAI,SAAmB,gBAAgB;AAE3D,YAAU,MAAM;AACd,QAA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AAM,cAAc,MAAM,UAAU,OAAO,EAAE,YAAY,MAAM,QAAQ,UAAU,OAAO,CAAC;AAAA,IACzF,CAAC,MAAM,UAAU,OAAO,YAAY,MAAM,QAAQ,UAAU,MAAM;AAAA,EACpE;AACF;","names":["api","jsx","useContext","useEffect","useContext","useEffect"]}
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"],"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 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: string): 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: string,\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"],"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,SAAmC;AACvF,QAAM,WAAW,SAAS,eAAe,SAAS;AAClD,MAAI,SAAU;AACd,QAAM,SAAS,SAAS,cAAc,QAAQ;AAC9C,SAAO,KAAK;AACZ,SAAO,Q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SAAS,OAAO,YAAY;AAAA,MACvD,UAAE;AACA,gBAAQ,KAAK;AAAA,MACf;AAAA,IACF;AAAA,IACA,CAAC,MAAM,MAAM,cAAc,OAAO;AAAA,EACpC;AACA,SACE,gBAAAC,KAAC,OAAE,MAAM,gBAAgB,KAAK,WAAsB,SAAkB,aAAW,QAAQ,QACtF,UACH;AAEJ;;;ACxDA,SAAS,aAAAC,YAAW,UAAAC,eAAc;AAoC9B,gBAAAC,YAAA;AAvBJ,IAAM,QAAQ,EAAE,QAAQ,GAAG;AAepB,SAAS,kBAAkB,EAAE,WAAW,WAAW,GAAG,GAA2B;AACtF,QAAM,MAAMD,QAAuB,IAAI;AACvC,EAAAD,WAAU,MAAM;AACd,UAAM,KAAK,IAAI;AACf,UAAM,MAAM,OAAO,WAAW,cAAc,OAAO,cAAc;AACjE,QAAI,MAAM,CAAC,GAAG,cAAc,EAAG,MAAK,KAAK,oBAAoB,EAAE,GAAG,QAAQ,MAAM;AAAA,IAAC,CAAC;AAAA,EACpF,GAAG,CAAC,CAAC;AACL,SACE,gBAAAE;AAAA,IAAC;AAAA;AAAA,MACC;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAQ;AAAA,MACP,GAAI,cAAc,SAAY,EAAE,cAAc,UAAU,IAAI,CAAC;AAAA,MAC9D,0BAAwB;AAAA,MACxB,yBAAyB;AAAA;AAAA,EAC3B;AAEJ;","names":["api","jsx","useContext","useEffect","useContext","useEffect","useState","jsx","useEffect","useRef","jsx"]}
package/dist/helpers.d.ts CHANGED
@@ -125,6 +125,13 @@ interface CookieMunchGlobal {
125
125
  submitCustomConsent(preferences: boolean, statistics: boolean, marketing: boolean): void;
126
126
  /** Subscribe to consent changes (accept/decline). Returns an unsubscribe fn. */
127
127
  onConsentChange(callback: (state: unknown) => void): () => void;
128
+ /**
129
+ * Whether `category` (a site category id or an alias such as `functional`) is consented.
130
+ * An unknown category answers false. Optional: older embeds lack it.
131
+ */
132
+ hasConsent?(category: string): boolean;
133
+ /** Draw the cookie declaration into `el` (all mounts when omitted). Optional: older embeds lack it. */
134
+ renderDeclaration?(el?: Element | null): Promise<void>;
128
135
  }
129
136
  /** Augment the browser `Window` with the embed's globals. */
130
137
  declare global {
@@ -133,4 +140,11 @@ declare global {
133
140
  }
134
141
  }
135
142
 
136
- export { CONSENT_COOKIE_NAME, type Category, type ConsentCookieOptions, type ConsentCookieState, type CookieMunchGlobal, type PublicConsent, consentCookie, isGranted, parseConsentCookie };
143
+ /**
144
+ * The URL shapes a minted link can have (docs: account-linked-rights): `https://<customDomain>/?t=…`
145
+ * when the site has an active custom rights domain, else `https://<app>/r/<cbid>?t=…`. Anything
146
+ * else — another scheme, no token — is refused rather than followed.
147
+ */
148
+ declare function isRightsLinkUrl(url: string, customDomain?: string | null): boolean;
149
+
150
+ export { CONSENT_COOKIE_NAME, type Category, type ConsentCookieOptions, type ConsentCookieState, type CookieMunchGlobal, type PublicConsent, consentCookie, isGranted, isRightsLinkUrl, parseConsentCookie };
package/dist/helpers.js CHANGED
@@ -94,10 +94,24 @@ function parseConsentCookie(raw) {
94
94
  }
95
95
  return state;
96
96
  }
97
+
98
+ // src/helpers.ts
99
+ function isRightsLinkUrl(url, customDomain) {
100
+ let u;
101
+ try {
102
+ u = new URL(url);
103
+ } catch {
104
+ return false;
105
+ }
106
+ if (u.protocol !== "https:" || !u.searchParams.get("t")) return false;
107
+ if (customDomain) return u.host === customDomain && u.pathname === "/";
108
+ return /^\/r\/[^/]+$/.test(u.pathname);
109
+ }
97
110
  export {
98
111
  CONSENT_COOKIE_NAME,
99
112
  consentCookie,
100
113
  isGranted,
114
+ isRightsLinkUrl,
101
115
  parseConsentCookie
102
116
  };
103
117
  //# sourceMappingURL=helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/consent-cookie.ts","../src/consent-parse.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","/**\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"],"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,UAA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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","/**\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 { CONSENT_COOKIE_NAME, parseConsentCookie, type ConsentCookieState } from './consent-parse.js';\nexport type { Category, 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,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aAAa,OAAO,cAAc,UAAW,QAAO;AAElH,MAAI,EAAE,WAAW,cAAc,EAAE,WAAW,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;;;AC7DO,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":[]}
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { ConsentContextValue, ConsentGate, ConsentGateProps, ConsentProvider, ConsentProviderProps, useConsent, useConsentCookie, useConsentValue } from './client.js';
2
- export { CONSENT_COOKIE_NAME, Category, ConsentCookieOptions, ConsentCookieState, CookieMunchGlobal, PublicConsent, consentCookie, isGranted, parseConsentCookie } from './helpers.js';
1
+ export { ConsentContextValue, ConsentGate, ConsentGateProps, ConsentProvider, ConsentProviderProps, CookieDeclaration, CookieDeclarationProps, MintedRightsLink, RightsLink, RightsLinkProps, useConsent, useConsentCookie, useConsentValue } from './client.js';
2
+ export { CONSENT_COOKIE_NAME, Category, ConsentCookieOptions, ConsentCookieState, CookieMunchGlobal, PublicConsent, consentCookie, isGranted, isRightsLinkUrl, parseConsentCookie } from './helpers.js';
package/dist/index.js CHANGED
@@ -4,20 +4,26 @@ import {
4
4
  useConsent,
5
5
  ConsentGate,
6
6
  useConsentValue,
7
- useConsentCookie
7
+ useConsentCookie,
8
+ RightsLink,
9
+ CookieDeclaration
8
10
  } from "./client.js";
9
11
  import {
10
12
  consentCookie,
11
13
  isGranted,
12
14
  CONSENT_COOKIE_NAME,
13
- parseConsentCookie
15
+ parseConsentCookie,
16
+ isRightsLinkUrl
14
17
  } from "./helpers.js";
15
18
  export {
16
19
  CONSENT_COOKIE_NAME,
17
20
  ConsentGate,
18
21
  ConsentProvider,
22
+ CookieDeclaration,
23
+ RightsLink,
19
24
  consentCookie,
20
25
  isGranted,
26
+ isRightsLinkUrl,
21
27
  parseConsentCookie,
22
28
  useConsent,
23
29
  useConsentCookie,
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} from './client.js';\nexport {\n consentCookie,\n isGranted,\n type ConsentCookieOptions,\n CONSENT_COOKIE_NAME,\n parseConsentCookie,\n type ConsentCookieState,\n type Category,\n type PublicConsent,\n type CookieMunchGlobal,\n} from './helpers.js';\n"],"mappings":";AAGA;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OAKK;","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 RightsLink,\n type RightsLinkProps,\n type MintedRightsLink,\n CookieDeclaration,\n type CookieDeclarationProps,\n} from './client.js';\nexport {\n consentCookie,\n isGranted,\n type ConsentCookieOptions,\n CONSENT_COOKIE_NAME,\n parseConsentCookie,\n isRightsLinkUrl,\n type ConsentCookieState,\n type Category,\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,EAGA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cookiemunch/react",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "React/Next wrapper for Cookie Munch",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",