@simmalugnt-se/payload-consent 0.0.0-stage → 0.1.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/LICENSE +21 -0
  3. package/README.md +238 -2
  4. package/dist/admin/ScanPanel.d.ts +3 -0
  5. package/dist/admin/ScanPanel.js +232 -0
  6. package/dist/block.d.ts +6 -0
  7. package/dist/block.js +27 -0
  8. package/dist/defaults.d.ts +56 -0
  9. package/dist/defaults.js +137 -0
  10. package/dist/evaluate.d.ts +106 -0
  11. package/dist/evaluate.js +101 -0
  12. package/dist/evidence.d.ts +12 -0
  13. package/dist/evidence.js +113 -0
  14. package/dist/exports/admin.d.ts +1 -0
  15. package/dist/exports/admin.js +1 -0
  16. package/dist/exports/client.d.ts +37 -0
  17. package/dist/exports/client.js +177 -0
  18. package/dist/exports/rsc.d.ts +1 -0
  19. package/dist/exports/rsc.js +1 -0
  20. package/dist/global.d.ts +14 -0
  21. package/dist/global.js +272 -0
  22. package/dist/index.d.ts +13 -0
  23. package/dist/index.js +75 -0
  24. package/dist/integrations.d.ts +40 -0
  25. package/dist/integrations.js +32 -0
  26. package/dist/notify.d.ts +15 -0
  27. package/dist/notify.js +86 -0
  28. package/dist/records.d.ts +15 -0
  29. package/dist/records.js +197 -0
  30. package/dist/scans.d.ts +37 -0
  31. package/dist/scans.js +423 -0
  32. package/dist/schedule.d.ts +17 -0
  33. package/dist/schedule.js +18 -0
  34. package/dist/services.d.ts +8 -0
  35. package/dist/services.js +257 -0
  36. package/dist/site-config.d.ts +128 -0
  37. package/dist/site-config.js +204 -0
  38. package/dist/styles/admin.css +144 -0
  39. package/dist/styles/consent.css +296 -0
  40. package/dist/types.d.ts +65 -0
  41. package/dist/types.js +17 -0
  42. package/dist/widget/ConsentScanWidget.d.ts +8 -0
  43. package/dist/widget/ConsentScanWidget.js +99 -0
  44. package/package.json +76 -3
@@ -0,0 +1,177 @@
1
+ "use client";
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { ConsentDialog as C15tDialog, ConsentBanner, ConsentManagerProvider, Frame, useConsentManager, } from "@c15t/react";
4
+ import { gtag } from "@c15t/scripts/google-tag";
5
+ import { googleTagManager } from "@c15t/scripts/google-tag-manager";
6
+ import { hotjar } from "@c15t/scripts/hotjar";
7
+ import { linkedinInsights } from "@c15t/scripts/linkedin-insights";
8
+ import { metaPixel } from "@c15t/scripts/meta-pixel";
9
+ import { clarity } from "@c15t/scripts/microsoft-clarity";
10
+ import { microsoftUet } from "@c15t/scripts/microsoft-uet";
11
+ import { tiktokPixel } from "@c15t/scripts/tiktok-pixel";
12
+ import { createContext, useContext, useEffect, useRef, } from "react";
13
+ import { POLICY_COOKIE } from "../types.js";
14
+ /** A button that opens the settings dialog, for the site's footer. Render it inside `ConsentProvider`. */
15
+ export { ConsentDialogLink as ConsentSettingsLink } from "@c15t/react";
16
+ /** Class names for c15t's unstyled parts, styled by `styles.css`. */
17
+ const slots = {
18
+ consentBanner: "sc-banner",
19
+ consentBannerCard: "sc-card",
20
+ consentBannerHeader: "sc-header",
21
+ consentBannerTitle: "sc-title",
22
+ consentBannerDescription: "sc-description",
23
+ consentBannerFooter: "sc-actions",
24
+ consentBannerFooterSubGroup: "sc-group",
25
+ consentDialog: "sc-dialog",
26
+ consentDialogCard: "sc-dialog-card",
27
+ consentDialogHeader: "sc-header",
28
+ consentDialogTitle: "sc-title",
29
+ consentDialogDescription: "sc-description",
30
+ consentDialogContent: "sc-content",
31
+ consentDialogOverlay: "sc-overlay",
32
+ consentWidget: "sc-widget",
33
+ consentWidgetAccordion: "sc-categories",
34
+ consentWidgetFooter: "sc-actions",
35
+ consentWidgetFooterSubGroup: "sc-group",
36
+ buttonPrimary: "sc-button",
37
+ buttonSecondary: "sc-button",
38
+ toggle: "sc-toggle",
39
+ consentBannerTag: "sc-branding",
40
+ consentDialogTag: "sc-branding",
41
+ };
42
+ const factories = {
43
+ googleTagManager: (id) => googleTagManager({ id }),
44
+ googleTag: (id, category) => gtag({ id, category }),
45
+ metaPixel: (pixelId) => metaPixel({ pixelId }),
46
+ linkedinInsights: (id) => linkedinInsights({ id }),
47
+ tiktokPixel: (pixelId) => tiktokPixel({ pixelId }),
48
+ microsoftUet: (id) => microsoftUet({ id }),
49
+ microsoftClarity: (id) => clarity({ id }),
50
+ hotjar: (siteId) => hotjar({ siteId }),
51
+ };
52
+ /**
53
+ * The services the plugin loads, each in its service's category. In basic consent mode nothing
54
+ * loads before consent, including tags c15t would otherwise load at once in a denied state.
55
+ */
56
+ export function integrationScripts(config) {
57
+ return config.integrations.map(({ key, id, category }) => ({
58
+ ...factories[key](id, category),
59
+ category,
60
+ ...(config.googleConsentMode === "basic" ? { alwaysLoad: false } : {}),
61
+ }));
62
+ }
63
+ const ConfigContext = createContext(null);
64
+ /** The banner, the settings dialog and c15t's consent state around the site. */
65
+ export function ConsentProvider({ config, scripts, children }) {
66
+ if (!config.enabled)
67
+ return _jsx(_Fragment, { children: children });
68
+ forgetOutdatedConsent(config.policyVersion);
69
+ const options = {
70
+ mode: "offline",
71
+ overrides: { country: "SE" },
72
+ consentCategories: config.categories,
73
+ scripts: [...integrationScripts(config), ...(scripts ?? [])],
74
+ legalLinks: config.legalLinks,
75
+ noStyle: true,
76
+ scrollLock: true,
77
+ theme: { slots },
78
+ i18n: {
79
+ locale: config.locale,
80
+ detectBrowserLanguage: false,
81
+ messages: { [config.locale]: config.messages },
82
+ },
83
+ };
84
+ // With only necessary storage there is nothing to reject: Settings and the Okay button remain.
85
+ const necessaryOnly = config.categories.length === 1;
86
+ return (_jsx(ConfigContext.Provider, { value: config, children: _jsxs(ConsentManagerProvider, { options: options, children: [children, _jsx(ConsentBanner, { hideBranding: true, layout: necessaryOnly ? [["customize", "accept"]] : undefined }), _jsx(SettingsDialog, {}), _jsx(ConsentRecorder, { config: config })] }) }));
87
+ }
88
+ function readPolicy() {
89
+ const match = document.cookie.match(new RegExp(`(?:^|; )${POLICY_COOKIE}=([^;]*)`));
90
+ return match ? decodeURIComponent(match[1] ?? "") : null;
91
+ }
92
+ const checkedPolicies = new Set();
93
+ /**
94
+ * Removes a choice made under another policy version before c15t reads it, so nothing it allowed
95
+ * loads before the visitor is asked again. Runs once per page load and version: a choice saved on
96
+ * this page writes the new version itself.
97
+ */
98
+ function forgetOutdatedConsent(version) {
99
+ if (typeof document === "undefined" || checkedPolicies.has(version))
100
+ return;
101
+ checkedPolicies.add(version);
102
+ if (readPolicy() === version || !/(?:^|; )c15t=/.test(document.cookie))
103
+ return;
104
+ document.cookie = "c15t=; Path=/; Max-Age=0";
105
+ try {
106
+ window.localStorage.removeItem("c15t");
107
+ }
108
+ catch {
109
+ // Without storage access there is nothing stored to remove.
110
+ }
111
+ }
112
+ function writePolicy(version) {
113
+ const secure = window.location.protocol === "https:" ? "; Secure" : "";
114
+ document.cookie = `${POLICY_COOKIE}=${encodeURIComponent(version)}; Path=/; Max-Age=${365 * 24 * 60 * 60}; SameSite=Lax${secure}`;
115
+ }
116
+ /** Posts each choice saved on this page to the site's consent records, with its policy version. */
117
+ function ConsentRecorder({ config }) {
118
+ const { consentInfo, consents } = useConsentManager();
119
+ const mountedAt = useRef(Date.now());
120
+ const savedAt = consentInfo?.time;
121
+ // biome-ignore lint/correctness/useExhaustiveDependencies: a new save time is a new choice.
122
+ useEffect(() => {
123
+ if (!savedAt || savedAt < mountedAt.current)
124
+ return;
125
+ writePolicy(config.policyVersion);
126
+ if (!config.recordUrl || !consentInfo?.subjectId)
127
+ return;
128
+ const choices = Object.fromEntries(config.categories.map((category) => [category, Boolean(consents[category])]));
129
+ fetch(config.recordUrl, {
130
+ method: "POST",
131
+ headers: { "Content-Type": "application/json" },
132
+ keepalive: true,
133
+ body: JSON.stringify({
134
+ subjectId: consentInfo.subjectId,
135
+ choices,
136
+ policyVersion: config.policyVersion,
137
+ locale: config.locale,
138
+ path: window.location.pathname,
139
+ }),
140
+ }).catch(() => {
141
+ // The choice still applies in the browser; only the record is missing.
142
+ });
143
+ }, [savedAt]);
144
+ return null;
145
+ }
146
+ /** c15t's dialog; a click on the backdrop discards unsaved toggles and returns to the banner. */
147
+ function SettingsDialog() {
148
+ const { consents, selectedConsents, setSelectedConsent, hasConsented, setActiveUI } = useConsentManager();
149
+ function dismiss(event) {
150
+ if (event.target !== event.currentTarget)
151
+ return;
152
+ for (const name of Object.keys(selectedConsents))
153
+ setSelectedConsent(name, consents[name] ?? false);
154
+ setActiveUI(hasConsented() ? "none" : "banner");
155
+ }
156
+ return (_jsx(C15tDialog.Root, { onClick: dismiss, children: _jsx(C15tDialog.ConsentCustomizationCard, { hideBranding: true }) }));
157
+ }
158
+ /**
159
+ * Embedded content, such as a video or a map, that is not mounted until the visitor allows its
160
+ * category. Until then a placeholder offers to allow it. Without the banner, the content shows.
161
+ */
162
+ export function ConsentFrame({ category, children, className }) {
163
+ const config = useContext(ConfigContext);
164
+ if (!config)
165
+ return _jsx(_Fragment, { children: children });
166
+ return (_jsx(Frame, { category: category, className: className, noStyle: true, placeholder: _jsx(EmbedPlaceholder, { category: category, config: config }), children: children }));
167
+ }
168
+ function EmbedPlaceholder({ category, config }) {
169
+ const { setConsent } = useConsentManager();
170
+ const title = config.messages.consentTypes?.[category]?.title ?? category;
171
+ return (_jsxs("div", { className: "sc-frame", children: [_jsx("p", { children: config.embeds.title.replaceAll("{category}", title) }), _jsx("button", { type: "button", onClick: () => setConsent(category, true), children: config.embeds.button.replaceAll("{category}", title) })] }));
172
+ }
173
+ /** The cookie services by category, from `getCookieTable`, for the site's cookie page. */
174
+ export function CookieTable({ data, heading }) {
175
+ const { labels } = data;
176
+ return (_jsxs("section", { className: "sc-cookie-table", children: [heading ? _jsx("h2", { children: heading }) : null, data.categories.map((category) => (_jsxs("section", { children: [_jsx("h3", { children: category.title }), _jsx("p", { children: category.description }), category.services.length ? null : _jsx("p", { children: labels.noServices }), category.services.map((service) => (_jsxs("div", { className: "sc-cookie-service", children: [_jsxs("h4", { children: [service.name, service.provider ? ` · ${service.provider}` : null] }), service.purpose ? _jsx("p", { children: service.purpose }) : null, service.policyUrl ? (_jsx("p", { children: _jsx("a", { href: service.policyUrl, rel: "noopener noreferrer", target: "_blank", children: labels.policy }) })) : null, service.storage.length ? (_jsxs("table", { children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { scope: "col", children: labels.name }), _jsx("th", { scope: "col", children: labels.type }), _jsx("th", { scope: "col", children: labels.duration }), _jsx("th", { scope: "col", children: labels.thirdParty }), _jsx("th", { scope: "col", children: labels.purpose })] }) }), _jsx("tbody", { children: service.storage.map((entry) => (_jsxs("tr", { children: [_jsx("td", { children: _jsx("code", { children: entry.name }) }), _jsx("td", { children: entry.type }), _jsx("td", { children: entry.duration ?? "–" }), _jsx("td", { children: entry.thirdParty ? labels.yes : labels.no }), _jsx("td", { children: entry.description ?? "–" })] }, `${entry.type}:${entry.name}`))) })] })) : null] }, service.name)))] }, category.key)))] }));
177
+ }
@@ -0,0 +1 @@
1
+ export { ConsentScanWidget } from "../widget/ConsentScanWidget.tsx";
@@ -0,0 +1 @@
1
+ export { ConsentScanWidget } from "../widget/ConsentScanWidget.js";
@@ -0,0 +1,14 @@
1
+ import type { GlobalConfig } from "payload";
2
+ import { type Category } from "./defaults.ts";
3
+ import type { ScanSchedule } from "./schedule.ts";
4
+ import { type ConsentPluginOptions } from "./types.ts";
5
+ type Label = {
6
+ en: string;
7
+ sv: string;
8
+ };
9
+ export declare const categoryLabels: Record<Category, Label>;
10
+ export declare function consentGlobal(options: ConsentPluginOptions, { usersSlug, schedule }: {
11
+ usersSlug: string;
12
+ schedule: ScanSchedule;
13
+ }): GlobalConfig;
14
+ export {};
package/dist/global.js ADDED
@@ -0,0 +1,272 @@
1
+ import { defaultTexts, OPTIONAL_CATEGORIES } from "./defaults.js";
2
+ import { CONSENT_GLOBAL } from "./types.js";
3
+ export const categoryLabels = {
4
+ necessary: { en: "Necessary", sv: "Nödvändiga" },
5
+ functionality: { en: "Functionality", sv: "Funktionalitet" },
6
+ experience: { en: "Experience", sv: "Upplevelse" },
7
+ measurement: { en: "Statistics", sv: "Statistik" },
8
+ marketing: { en: "Marketing", sv: "Marknadsföring" },
9
+ };
10
+ const hasOptional = (data) => Boolean(data?.categories?.length);
11
+ /**
12
+ * A localized text prefilled with the suggestion for the language being edited. Not required: an
13
+ * empty text shows the suggestion, and adding a text later needs no value for saved documents.
14
+ */
15
+ function text(name, label, suggestion, extra = {}) {
16
+ return {
17
+ name,
18
+ type: extra.textarea ? "textarea" : "text",
19
+ label,
20
+ localized: true,
21
+ defaultValue: ({ locale }) => suggestion(defaultTexts(locale)),
22
+ admin: {
23
+ ...(extra.width ? { width: extra.width } : {}),
24
+ ...(extra.description ? { description: extra.description } : {}),
25
+ ...(extra.condition ? { condition: (data) => extra.condition?.(data) ?? true } : {}),
26
+ },
27
+ };
28
+ }
29
+ const BUTTON_WIDTH = "33%";
30
+ const withChoices = {
31
+ description: {
32
+ en: "Shown when visitors can choose optional categories.",
33
+ sv: "Visas när besökaren kan välja valfria kategorier.",
34
+ },
35
+ condition: hasOptional,
36
+ };
37
+ const necessaryOnly = {
38
+ description: {
39
+ en: "Shown when the site only uses necessary storage.",
40
+ sv: "Visas när webbplatsen bara använder nödvändig lagring.",
41
+ },
42
+ condition: (data) => !hasOptional(data),
43
+ };
44
+ export function consentGlobal(options, { usersSlug, schedule }) {
45
+ const time = `${String(schedule.hour).padStart(2, "0")}:${String(schedule.minute).padStart(2, "0")}`;
46
+ const legal = options.legalPages;
47
+ const global = {
48
+ slug: CONSENT_GLOBAL,
49
+ label: { en: "Cookies", sv: "Cookies" },
50
+ admin: { group: options.group ?? { en: "Settings", sv: "Inställningar" } },
51
+ access: { read: () => true, ...options.access },
52
+ fields: [
53
+ {
54
+ type: "tabs",
55
+ tabs: [
56
+ {
57
+ label: { en: "Banner", sv: "Banner" },
58
+ description: {
59
+ en: "What visitors see before they choose. Accept and reject are always shown side by side.",
60
+ sv: "Det besökaren ser innan hen har valt. Godkänn och avvisa visas alltid sida vid sida.",
61
+ },
62
+ fields: [
63
+ text("bannerTitle", { en: "Title", sv: "Rubrik" }, (t) => t.bannerTitle),
64
+ text("bannerDescription", { en: "Description", sv: "Beskrivning" }, (t) => t.bannerDescription, { textarea: true, ...withChoices }),
65
+ text("bannerDescriptionNecessaryOnly", { en: "Description", sv: "Beskrivning" }, (t) => t.bannerDescriptionNecessaryOnly, { textarea: true, ...necessaryOnly }),
66
+ {
67
+ name: "buttons",
68
+ type: "group",
69
+ label: { en: "Buttons", sv: "Knappar" },
70
+ fields: [
71
+ {
72
+ type: "row",
73
+ fields: [
74
+ text("acceptAll", { en: "Accept all", sv: "Godkänn alla" }, (t) => t.buttons.acceptAll, { condition: hasOptional, width: BUTTON_WIDTH }),
75
+ text("acceptNecessaryOnly", { en: "Accept", sv: "Godkänn" }, (t) => t.buttons.acceptNecessaryOnly, { condition: necessaryOnly.condition, width: BUTTON_WIDTH }),
76
+ text("rejectAll", { en: "Reject optional", sv: "Avvisa valfria" }, (t) => t.buttons.rejectAll, { condition: hasOptional, width: BUTTON_WIDTH }),
77
+ ],
78
+ },
79
+ {
80
+ type: "row",
81
+ fields: [
82
+ text("customize", { en: "Settings", sv: "Inställningar" }, (t) => t.buttons.customize, { width: BUTTON_WIDTH }),
83
+ text("save", { en: "Save choices", sv: "Spara val" }, (t) => t.buttons.save, {
84
+ width: BUTTON_WIDTH,
85
+ }),
86
+ text("close", { en: "Close", sv: "Stäng" }, (t) => t.buttons.close, {
87
+ width: BUTTON_WIDTH,
88
+ }),
89
+ ],
90
+ },
91
+ ],
92
+ },
93
+ {
94
+ name: "dialog",
95
+ type: "group",
96
+ label: { en: "Settings dialog", sv: "Inställningsdialog" },
97
+ fields: [
98
+ text("title", { en: "Title", sv: "Rubrik" }, (t) => t.dialog.title),
99
+ text("description", { en: "Description", sv: "Beskrivning" }, (t) => t.dialog.description, { textarea: true, ...withChoices }),
100
+ text("descriptionNecessaryOnly", { en: "Description", sv: "Beskrivning" }, (t) => t.dialog.descriptionNecessaryOnly, { textarea: true, ...necessaryOnly }),
101
+ ],
102
+ },
103
+ {
104
+ name: "embeds",
105
+ type: "group",
106
+ label: { en: "Embedded content", sv: "Inbäddat innehåll" },
107
+ admin: {
108
+ description: {
109
+ en: "Shown in place of a video, map or other embed until the visitor allows its category. {category} becomes the category's title.",
110
+ sv: "Visas i stället för en video, karta eller annan inbäddning tills besökaren tillåter dess kategori. {category} blir kategorins rubrik.",
111
+ },
112
+ },
113
+ fields: [
114
+ {
115
+ type: "row",
116
+ fields: [
117
+ text("title", { en: "Text", sv: "Text" }, (t) => t.embeds.title, {
118
+ width: "66%",
119
+ }),
120
+ text("button", { en: "Button", sv: "Knapp" }, (t) => t.embeds.button, {
121
+ width: "34%",
122
+ }),
123
+ ],
124
+ },
125
+ ],
126
+ },
127
+ {
128
+ name: "categoryTexts",
129
+ type: "group",
130
+ label: { en: "Categories", sv: "Kategorier" },
131
+ fields: ["necessary", ...OPTIONAL_CATEGORIES].map((category) => ({
132
+ name: category,
133
+ type: "group",
134
+ label: categoryLabels[category],
135
+ admin: category === "necessary"
136
+ ? {}
137
+ : {
138
+ condition: (data) => Boolean(data?.categories?.includes(category)),
139
+ },
140
+ fields: [
141
+ text("title", { en: "Title", sv: "Rubrik" }, (t) => t.categoryTexts[category].title),
142
+ text("description", { en: "Description", sv: "Beskrivning" }, (t) => t.categoryTexts[category].description, { textarea: true }),
143
+ ],
144
+ })),
145
+ },
146
+ ],
147
+ },
148
+ {
149
+ label: { en: "Scan", sv: "Skanning" },
150
+ description: {
151
+ en: "Scans the published site as a new visitor, after rejecting and after accepting, and compares what it finds with the Cookie services.",
152
+ sv: "Skannar den publicerade webbplatsen som ny besökare, efter avvisa och efter godkänn, och jämför det som hittas med Cookietjänsterna.",
153
+ },
154
+ fields: [
155
+ {
156
+ name: "scanUrl",
157
+ type: "text",
158
+ label: { en: "Site address", sv: "Webbplatsens adress" },
159
+ admin: {
160
+ placeholder: "https://",
161
+ description: {
162
+ en: "The published site's start page. Empty: the site's own address (serverURL).",
163
+ sv: "Den publicerade webbplatsens startsida. Tom: webbplatsens egen adress (serverURL).",
164
+ },
165
+ },
166
+ },
167
+ {
168
+ name: "scheduledScans",
169
+ type: "checkbox",
170
+ defaultValue: true,
171
+ label: { en: "Scan every month", sv: "Skanna varje månad" },
172
+ admin: {
173
+ description: {
174
+ en: `On day ${schedule.day} of each month, the first time the host's cron runs Payload's jobs after ${time} server time.`,
175
+ sv: `Den ${schedule.day}:e varje månad, första gången värdens cron kör Payloads jobb efter kl. ${time} servertid.`,
176
+ },
177
+ },
178
+ },
179
+ {
180
+ name: "notify",
181
+ type: "relationship",
182
+ relationTo: usersSlug,
183
+ hasMany: true,
184
+ label: { en: "Email about scans", sv: "Mejla om skanningar" },
185
+ admin: {
186
+ description: {
187
+ en: "Gets an email when a scan fails, finds something to handle or finds something new.",
188
+ sv: "Får ett mejl när en skanning misslyckas, hittar något att åtgärda eller hittar något nytt.",
189
+ },
190
+ },
191
+ },
192
+ {
193
+ name: "scanPanel",
194
+ type: "ui",
195
+ admin: {
196
+ components: { Field: "@simmalugnt-se/payload-consent/admin#ScanPanel" },
197
+ },
198
+ },
199
+ ],
200
+ },
201
+ {
202
+ label: { en: "Settings", sv: "Inställningar" },
203
+ fields: [
204
+ {
205
+ name: "enabled",
206
+ type: "checkbox",
207
+ label: { en: "Show the cookie banner", sv: "Visa cookiebannern" },
208
+ defaultValue: true,
209
+ },
210
+ {
211
+ name: "categories",
212
+ type: "select",
213
+ hasMany: true,
214
+ label: { en: "Optional categories", sv: "Valfria kategorier" },
215
+ admin: {
216
+ readOnly: true,
217
+ description: {
218
+ en: "Follows the categories of the Cookie services. With none, the banner only informs and has an Okay button.",
219
+ sv: "Följer kategorierna under Cookietjänster. Utan valfria kategorier informerar bannern bara och har en Okej-knapp.",
220
+ },
221
+ },
222
+ options: OPTIONAL_CATEGORIES.map((value) => ({
223
+ value,
224
+ label: categoryLabels[value],
225
+ })),
226
+ },
227
+ {
228
+ name: "googleConsentMode",
229
+ type: "radio",
230
+ defaultValue: "basic",
231
+ label: { en: "Google Consent Mode", sv: "Google Consent Mode" },
232
+ options: [
233
+ {
234
+ value: "basic",
235
+ label: {
236
+ en: "Basic: nothing loads before consent",
237
+ sv: "Basic: inget laddas före samtycke",
238
+ },
239
+ },
240
+ {
241
+ value: "advanced",
242
+ label: {
243
+ en: "Advanced: Google and similar tags load at once in a denied state",
244
+ sv: "Advanced: Google och liknande taggar laddas direkt i nekat läge",
245
+ },
246
+ },
247
+ ],
248
+ admin: {
249
+ description: {
250
+ en: "Applies to the services the plugin loads. Advanced sends cookieless measurements to the provider before the visitor has chosen; pick it only when that has been assessed as acceptable.",
251
+ sv: "Gäller tjänsterna som pluginet laddar. Advanced skickar mätningar utan cookies till leverantören innan besökaren har valt; välj det bara när det har bedömts som godtagbart.",
252
+ },
253
+ },
254
+ },
255
+ ...(legal
256
+ ? ["privacyPolicy", "cookiePolicy"].map((name) => ({
257
+ name,
258
+ type: "relationship",
259
+ relationTo: legal.collection,
260
+ label: name === "privacyPolicy"
261
+ ? { en: "Privacy policy", sv: "Integritetspolicy" }
262
+ : { en: "Cookie policy", sv: "Cookiepolicy" },
263
+ }))
264
+ : []),
265
+ ],
266
+ },
267
+ ],
268
+ },
269
+ ],
270
+ };
271
+ return options.overrideGlobal ? options.overrideGlobal(global) : global;
272
+ }
@@ -0,0 +1,13 @@
1
+ import type { Plugin } from "payload";
2
+ import { type ConsentPluginOptions } from "./types.ts";
3
+ export { cookieTableBlock } from "./block.ts";
4
+ export { CATEGORIES, type Category, defaultTexts, OPTIONAL_CATEGORIES } from "./defaults.ts";
5
+ export { evaluateScan, type Finding, type FindingStatus, type ScanResultState, type ScanState, } from "./evaluate.ts";
6
+ export { INTEGRATIONS, type IntegrationKey } from "./integrations.ts";
7
+ export { notifyScan, type ScanOutcome } from "./notify.ts";
8
+ export { type ConsentRecordInput, parseRecord } from "./records.ts";
9
+ export { scanStates, startScan } from "./scans.ts";
10
+ export { nextScan, type ScanSchedule, scanSchedule } from "./schedule.ts";
11
+ export { type ConsentConfig, type ConsentDocument, type CookieTableData, getConsentConfig, getCookieTable, policyVersion, type ServiceDocument, toConsentConfig, toCookieTable, } from "./site-config.ts";
12
+ export { CONSENT_GLOBAL, CONSENT_POLICIES, CONSENT_RECORDS, CONSENT_SCAN_EVIDENCE, CONSENT_SCANS, CONSENT_SERVICES, type ConsentPluginOptions, SCAN_TASK, SCAN_WIDGET, } from "./types.ts";
13
+ export declare function consentPlugin(options?: ConsentPluginOptions): Plugin;
package/dist/index.js ADDED
@@ -0,0 +1,75 @@
1
+ import { evidenceCollection } from "./evidence.js";
2
+ import { consentGlobal } from "./global.js";
3
+ import { policiesCollection, recordsCollection } from "./records.js";
4
+ import { scansCollection, scanTask } from "./scans.js";
5
+ import { scanSchedule } from "./schedule.js";
6
+ import { servicesCollection } from "./services.js";
7
+ import { CONSENT_GLOBAL, CONSENT_POLICIES, CONSENT_RECORDS, CONSENT_SCAN_EVIDENCE, CONSENT_SCANS, CONSENT_SERVICES, SCAN_WIDGET, } from "./types.js";
8
+ export { cookieTableBlock } from "./block.js";
9
+ export { CATEGORIES, defaultTexts, OPTIONAL_CATEGORIES } from "./defaults.js";
10
+ export { evaluateScan, } from "./evaluate.js";
11
+ export { INTEGRATIONS } from "./integrations.js";
12
+ export { notifyScan } from "./notify.js";
13
+ export { parseRecord } from "./records.js";
14
+ export { scanStates, startScan } from "./scans.js";
15
+ export { nextScan, scanSchedule } from "./schedule.js";
16
+ export { getConsentConfig, getCookieTable, policyVersion, toConsentConfig, toCookieTable, } from "./site-config.js";
17
+ export { CONSENT_GLOBAL, CONSENT_POLICIES, CONSENT_RECORDS, CONSENT_SCAN_EVIDENCE, CONSENT_SCANS, CONSENT_SERVICES, SCAN_TASK, SCAN_WIDGET, } from "./types.js";
18
+ const widget = {
19
+ slug: SCAN_WIDGET,
20
+ Component: "@simmalugnt-se/payload-consent/rsc#ConsentScanWidget",
21
+ label: { en: "Cookie scan", sv: "Cookieskanning" },
22
+ minWidth: "small",
23
+ };
24
+ export function consentPlugin(options = {}) {
25
+ return (config) => {
26
+ if (options.disabled)
27
+ return config;
28
+ if (config.globals?.some((global) => global.slug === CONSENT_GLOBAL))
29
+ throw new Error(`The ${CONSENT_GLOBAL} global slug is already in use`);
30
+ for (const slug of [
31
+ CONSENT_SERVICES,
32
+ CONSENT_RECORDS,
33
+ CONSENT_POLICIES,
34
+ CONSENT_SCANS,
35
+ CONSENT_SCAN_EVIDENCE,
36
+ ])
37
+ if (config.collections?.some((collection) => collection.slug === slug))
38
+ throw new Error(`The ${slug} collection slug is already in use`);
39
+ if (options.legalPages &&
40
+ !config.collections?.some((collection) => collection.slug === options.legalPages?.collection))
41
+ throw new Error(`Unknown legal pages collection: ${options.legalPages.collection}`);
42
+ // The site's own address spreads monthly scans over the month; the secret when it has none.
43
+ const schedule = scanSchedule(config.serverURL || config.secret || CONSENT_GLOBAL);
44
+ const usersSlug = config.admin?.user ?? "users";
45
+ return {
46
+ ...config,
47
+ collections: [
48
+ ...(config.collections ?? []),
49
+ servicesCollection(options),
50
+ ...(options.records === false
51
+ ? []
52
+ : [recordsCollection(options), policiesCollection(options)]),
53
+ scansCollection(options),
54
+ evidenceCollection(options),
55
+ ],
56
+ globals: [...(config.globals ?? []), consentGlobal(options, { usersSlug, schedule })],
57
+ // The monthly scan runs through Payload's jobs; added with or without a scanner, so the
58
+ // schema does not depend on the environment.
59
+ jobs: {
60
+ ...config.jobs,
61
+ tasks: [...(config.jobs?.tasks ?? []), scanTask(options, schedule)],
62
+ },
63
+ custom: { ...config.custom, consent: options, consentSchedule: schedule },
64
+ admin: {
65
+ ...config.admin,
66
+ // What the Scan tab needs to know in the browser; the token stays on the server.
67
+ custom: { ...config.admin?.custom, consent: { scanner: Boolean(options.scanner) } },
68
+ dashboard: {
69
+ ...config.admin?.dashboard,
70
+ widgets: [...(config.admin?.dashboard?.widgets ?? []), widget],
71
+ },
72
+ },
73
+ };
74
+ };
75
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The c15t script integrations an editor can pick for a service, from `@c15t/scripts` 2.2.0. A
3
+ * picked integration is loaded by c15t and follows the visitor's choice. The client imports each
4
+ * one, so the list stays short: the services our sites use, not the whole registry.
5
+ */
6
+ export declare const INTEGRATIONS: readonly [{
7
+ readonly key: "googleTagManager";
8
+ readonly label: "Google Tag Manager";
9
+ readonly idLabel: "Container ID (GTM-…)";
10
+ }, {
11
+ readonly key: "googleTag";
12
+ readonly label: "Google Analytics 4 / Google tag";
13
+ readonly idLabel: "Measurement ID (G-…)";
14
+ }, {
15
+ readonly key: "metaPixel";
16
+ readonly label: "Meta Pixel";
17
+ readonly idLabel: "Pixel ID";
18
+ }, {
19
+ readonly key: "linkedinInsights";
20
+ readonly label: "LinkedIn Insight Tag";
21
+ readonly idLabel: "Partner ID";
22
+ }, {
23
+ readonly key: "tiktokPixel";
24
+ readonly label: "TikTok Pixel";
25
+ readonly idLabel: "Pixel ID";
26
+ }, {
27
+ readonly key: "microsoftUet";
28
+ readonly label: "Microsoft Ads (UET)";
29
+ readonly idLabel: "Tag ID";
30
+ }, {
31
+ readonly key: "microsoftClarity";
32
+ readonly label: "Microsoft Clarity";
33
+ readonly idLabel: "Project ID";
34
+ }, {
35
+ readonly key: "hotjar";
36
+ readonly label: "Hotjar";
37
+ readonly idLabel: "Site ID";
38
+ }];
39
+ export type IntegrationKey = (typeof INTEGRATIONS)[number]["key"];
40
+ export declare const isIntegration: (value: unknown) => value is IntegrationKey;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The c15t script integrations an editor can pick for a service, from `@c15t/scripts` 2.2.0. A
3
+ * picked integration is loaded by c15t and follows the visitor's choice. The client imports each
4
+ * one, so the list stays short: the services our sites use, not the whole registry.
5
+ */
6
+ export const INTEGRATIONS = [
7
+ {
8
+ key: "googleTagManager",
9
+ label: "Google Tag Manager",
10
+ idLabel: "Container ID (GTM-…)",
11
+ },
12
+ {
13
+ key: "googleTag",
14
+ label: "Google Analytics 4 / Google tag",
15
+ idLabel: "Measurement ID (G-…)",
16
+ },
17
+ { key: "metaPixel", label: "Meta Pixel", idLabel: "Pixel ID" },
18
+ {
19
+ key: "linkedinInsights",
20
+ label: "LinkedIn Insight Tag",
21
+ idLabel: "Partner ID",
22
+ },
23
+ { key: "tiktokPixel", label: "TikTok Pixel", idLabel: "Pixel ID" },
24
+ { key: "microsoftUet", label: "Microsoft Ads (UET)", idLabel: "Tag ID" },
25
+ {
26
+ key: "microsoftClarity",
27
+ label: "Microsoft Clarity",
28
+ idLabel: "Project ID",
29
+ },
30
+ { key: "hotjar", label: "Hotjar", idLabel: "Site ID" },
31
+ ];
32
+ export const isIntegration = (value) => INTEGRATIONS.some((integration) => integration.key === value);
@@ -0,0 +1,15 @@
1
+ import type { Payload } from "payload";
2
+ import type { ScanSummary } from "./evaluate.ts";
3
+ export type ScanOutcome = {
4
+ url: string;
5
+ status: "done" | "failed";
6
+ error?: string | null;
7
+ summary?: ScanSummary | null;
8
+ };
9
+ /** A scan worth an email: it failed, found something to handle, or found something new. */
10
+ export declare function needsNotice(outcome: ScanOutcome): boolean;
11
+ /**
12
+ * Emails the users picked under Cookies → Scan about a finished scan, through the host's
13
+ * email adapter, when it needs a look. Admin's default language picks the text.
14
+ */
15
+ export declare function notifyScan(payload: Payload, outcome: ScanOutcome): Promise<void>;