@consentry/next
Version:
Next.js + React integration layer for the Consentry SDK. Manages cookie preferences, script injection, and analytics sync.
187 lines (181 loc) • 6.81 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
ConsentManagerProvider: () => ConsentManagerProvider,
Scripts: () => Scripts,
useConsentManager: () => useConsentManager
});
module.exports = __toCommonJS(index_exports);
// src/Scripts.tsx
var import_script = __toESM(require("next/script"));
var import_react2 = __toESM(require("react"));
// src/ConsentManagerProvider.tsx
var import_react = require("react");
var import_core = require("@consentry/core");
var import_jsx_runtime = require("react/jsx-runtime");
var ConsentManagerContext = (0, import_react.createContext)(void 0);
var ConsentManagerProvider = ({
config,
children
}) => {
const [cookiePreferences, setCookiePreferencesState] = (0, import_react.useState)({
...import_core.fallbackDefaults,
...config.defaults
});
const [showConsentBanner, setShowConsentBanner] = (0, import_react.useState)(false);
const [isConsentKnown, setIsConsentKnown] = (0, import_react.useState)(false);
(0, import_react.useEffect)(() => {
const saved = (0, import_core.getConsentPreferences)();
if (saved) {
setCookiePreferencesState(saved);
setShowConsentBanner(false);
} else {
setShowConsentBanner(true);
}
setIsConsentKnown(true);
}, []);
const setCookiePreferences = (prefs) => {
setCookiePreferencesState(prefs);
(0, import_core.setConsentPreferences)(prefs);
setShowConsentBanner(false);
const { performance, advertising, social } = prefs;
(0, import_core.updateConsentSettings)("update", {
analytics_storage: performance ? "granted" : "denied",
ad_storage: advertising ? "granted" : "denied",
ad_user_data: advertising ? "granted" : "denied",
ad_personalization: social ? "granted" : "denied"
});
};
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
ConsentManagerContext.Provider,
{
value: {
cookiePreferences,
setCookiePreferences,
showConsentBanner,
isConsentKnown
},
children: [
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Scripts, { config }),
children
]
}
);
};
var useConsentManager = () => {
const ctx = (0, import_react.useContext)(ConsentManagerContext);
if (!ctx) {
throw new Error("useConsentManager must be used within a ConsentManagerProvider");
}
const { cookiePreferences, setCookiePreferences, showConsentBanner, isConsentKnown } = ctx;
const setCategoryConsent = (category, value) => {
setCookiePreferences({
...cookiePreferences,
[category]: value
});
};
const hasConsentedTo = (category) => cookiePreferences[category] === true;
return {
cookiePreferences,
setCookiePreferences,
setCategoryConsent,
hasConsentedTo,
showConsentBanner,
isConsentKnown
};
};
// src/Scripts.tsx
var import_core2 = require("@consentry/core");
// src/utils/extractScriptTagAttrs.ts
function extractScriptTagAttrs(html) {
if (typeof window === "undefined") return null;
try {
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
const scriptEl = doc.querySelector("script");
if (!scriptEl) return null;
const src = scriptEl.getAttribute("src") || void 0;
const attrs = {};
for (const attr of Array.from(scriptEl.attributes)) {
attrs[attr.name] = attr.value;
}
return { src, attrs };
} catch (e) {
console.warn("[consentry] Failed to parse script content:", e);
return null;
}
}
// src/Scripts.tsx
var import_jsx_runtime2 = require("react/jsx-runtime");
function Scripts({ config }) {
const { cookiePreferences, isConsentKnown } = useConsentManager();
const debug = config.debug ?? false;
if (!isConsentKnown) return null;
const allowedScripts = (0, import_core2.getAllowedScripts)(config, cookiePreferences, debug);
const handleScriptError = (id, src) => {
console.warn(`[consentry] Script "${id}" failed to load.`, { src });
};
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children: allowedScripts.map((script) => {
let parsed = null;
if (script.content?.trim().startsWith("<script")) {
parsed = extractScriptTagAttrs(script.content);
if (parsed) {
if (debug) {
console.warn(
`[consentry] Script "${script.id}" used <script> in content. Parsed as src-based script for safety.`
);
}
}
}
const isInline = !parsed && script.content;
return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_react2.default.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
import_script.default,
{
id: script.id,
strategy: script.strategy || "afterInteractive",
src: parsed?.src || script.src,
dangerouslySetInnerHTML: isInline ? { __html: script.content } : void 0,
onError: () => handleScriptError(script.id, parsed?.src || script.src),
...parsed?.attrs || script.attributes || {}
}
),
script.noscript && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("noscript", { dangerouslySetInnerHTML: { __html: script.noscript } })
] }, script.id);
}) });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ConsentManagerProvider,
Scripts,
useConsentManager
});
//# sourceMappingURL=index.js.map