@rcooler/consent 0.0.0-stage → 0.1.1

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/ui.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ import type { ConsentController } from "./types.js";
2
+ export interface Labels {
3
+ accept: string;
4
+ reject: string;
5
+ customize: string;
6
+ settings: string;
7
+ save: string;
8
+ close: string;
9
+ necessary: string;
10
+ preferences: string;
11
+ analytics: string;
12
+ marketing: string;
13
+ always: string;
14
+ privacy: string;
15
+ provider: string;
16
+ destination: string;
17
+ storage: string;
18
+ pending: string;
19
+ failed: string;
20
+ inventory: string;
21
+ sale: string;
22
+ sharing: string;
23
+ targeted_advertising: string;
24
+ sensitive_data: string;
25
+ optOut: string;
26
+ gpc: string;
27
+ privacyRights: string;
28
+ requestRights: string;
29
+ appeal: string;
30
+ processingUnknown: string;
31
+ region: string;
32
+ globalStrict: string;
33
+ rightsScope: string;
34
+ saleProcessing: string;
35
+ sharingProcessing: string;
36
+ advertisingProcessing: string;
37
+ sensitiveProcessing: string;
38
+ }
39
+ export declare const english: Labels;
40
+ export declare const ukrainian: Labels;
41
+ export interface UIOptions {
42
+ locale?: string;
43
+ direction?: "ltr" | "rtl";
44
+ translations?: Partial<Labels>;
45
+ container?: HTMLElement;
46
+ }
47
+ export interface ConsentUI {
48
+ open(opener?: HTMLElement): void;
49
+ destroy(): void;
50
+ }
51
+ export declare function mountConsent(controller: ConsentController, options?: UIOptions): ConsentUI;
package/dist/ui.js ADDED
@@ -0,0 +1,348 @@
1
+ import { resolveNoticeLocale } from "./validation.js";
2
+ import { regionalNotices, regionalRights, restrictionNames } from "./regional.js";
3
+ export const english = {
4
+ accept: "Accept all",
5
+ reject: "Reject optional",
6
+ customize: "Customize",
7
+ settings: "Privacy preferences",
8
+ save: "Save preferences",
9
+ close: "Close",
10
+ necessary: "Necessary",
11
+ preferences: "Preferences",
12
+ analytics: "Analytics",
13
+ marketing: "Marketing",
14
+ always: "Always active",
15
+ privacy: "Privacy policy",
16
+ provider: "Provider",
17
+ destination: "Destination",
18
+ storage: "Storage",
19
+ pending: "Saving your choice…",
20
+ failed: "Your choice could not be saved. Optional services remain off. Please try again.",
21
+ inventory: "Services and storage",
22
+ sale: "Do not sell my personal information",
23
+ sharing: "Do not share my personal information for cross-context advertising",
24
+ targeted_advertising: "Opt out of targeted advertising",
25
+ sensitive_data: "Limit use of sensitive personal information",
26
+ optOut: "Do not sell or share my personal information",
27
+ gpc: "Global Privacy Control is active. Sale, sharing and targeted advertising are blocked.",
28
+ privacyRights: "Your privacy choices",
29
+ requestRights: "Request access, correction or deletion",
30
+ appeal: "Appeal a privacy decision",
31
+ processingUnknown: "Data uses have not been classified. Privacy opt-outs block this optional service.",
32
+ region: "Privacy region",
33
+ globalStrict: "Unknown or unreviewed location — optional services require consent",
34
+ rightsScope: "These controls apply to this site's registered services. Use the privacy policy or request link for account data and other processing.",
35
+ saleProcessing: "Sale of personal information",
36
+ sharingProcessing: "Sharing for cross-context advertising",
37
+ advertisingProcessing: "Targeted advertising",
38
+ sensitiveProcessing: "Use of sensitive personal information",
39
+ };
40
+ export const ukrainian = {
41
+ accept: "Прийняти все",
42
+ reject: "Відхилити необов’язкові",
43
+ customize: "Налаштувати",
44
+ settings: "Налаштування приватності",
45
+ save: "Зберегти налаштування",
46
+ close: "Закрити",
47
+ necessary: "Необхідні",
48
+ preferences: "Налаштування",
49
+ analytics: "Аналітика",
50
+ marketing: "Маркетинг",
51
+ always: "Завжди активні",
52
+ privacy: "Політика приватності",
53
+ provider: "Постачальник",
54
+ destination: "Призначення",
55
+ storage: "Сховище",
56
+ pending: "Зберігаємо ваш вибір…",
57
+ failed: "Не вдалося зберегти вибір. Необов’язкові сервіси вимкнені. Спробуйте ще раз.",
58
+ inventory: "Сервіси та сховища",
59
+ sale: "Не продавати мої персональні дані",
60
+ sharing: "Не передавати мої персональні дані для міжконтекстної реклами",
61
+ targeted_advertising: "Відмовитися від цільової реклами",
62
+ sensitive_data: "Обмежити використання чутливих персональних даних",
63
+ optOut: "Не продавати й не передавати мої персональні дані",
64
+ gpc: "Global Privacy Control активний. Продаж, передавання даних і цільову рекламу заблоковано.",
65
+ privacyRights: "Ваш вибір щодо приватності",
66
+ requestRights: "Запит на доступ, виправлення або видалення",
67
+ appeal: "Оскаржити рішення щодо приватності",
68
+ processingUnknown: "Використання даних не класифіковано. Відмова блокує цей необов’язковий сервіс.",
69
+ region: "Регіон приватності",
70
+ globalStrict: "Невідоме або не перевірене місце — необов’язкові сервіси потребують згоди",
71
+ rightsScope: "Ці налаштування діють для зареєстрованих сервісів сайту. Для даних облікового запису й іншої обробки скористайтеся політикою приватності або посиланням запиту.",
72
+ saleProcessing: "Продаж персональних даних",
73
+ sharingProcessing: "Передавання даних для міжконтекстної реклами",
74
+ advertisingProcessing: "Цільова реклама",
75
+ sensitiveProcessing: "Використання чутливих персональних даних",
76
+ };
77
+ function element(tag, text) {
78
+ const node = document.createElement(tag);
79
+ if (text !== undefined)
80
+ node.textContent = text;
81
+ return node;
82
+ }
83
+ function button(text, action) {
84
+ const node = element("button", text);
85
+ node.type = "button";
86
+ node.className = "consent-action";
87
+ node.addEventListener("click", action);
88
+ return node;
89
+ }
90
+ export function mountConsent(controller, options = {}) {
91
+ const requestedLocale = options.locale ?? (document.documentElement.lang || "en");
92
+ const locale = regionalNotices(controller.state.config, requestedLocale)[0]?.locale ??
93
+ resolveNoticeLocale(controller.state.config.policy, requestedLocale);
94
+ const labels = {
95
+ ...(locale.toLowerCase().startsWith("uk") ? ukrainian : english),
96
+ ...options.translations,
97
+ };
98
+ const host = element("div");
99
+ host.className = options.container ? "consent-root consent-preview" : "consent-root";
100
+ host.lang = locale;
101
+ host.dir = options.direction ?? (document.documentElement.dir === "rtl" ? "rtl" : "ltr");
102
+ const banner = element("section");
103
+ banner.className = "consent-banner";
104
+ banner.setAttribute("role", "region");
105
+ const title = element("h2");
106
+ const description = element("p");
107
+ const privacy = element("a", labels.privacy);
108
+ privacy.rel = "noopener noreferrer";
109
+ const status = element("p");
110
+ status.className = "consent-status";
111
+ status.setAttribute("role", "status");
112
+ status.setAttribute("aria-live", "polite");
113
+ const actions = element("div");
114
+ actions.className = "consent-actions";
115
+ const accept = button(labels.accept, () => {
116
+ void controller.decide({ preferences: true, analytics: true, marketing: true }, locale);
117
+ });
118
+ const reject = button(labels.reject, () => {
119
+ void controller.decide({ preferences: false, analytics: false, marketing: false }, locale);
120
+ closeDialog();
121
+ });
122
+ const customize = button(labels.customize, () => openDialog(customize));
123
+ actions.append(accept, reject, customize);
124
+ banner.append(title, description, privacy, actions);
125
+ const settings = button(labels.settings, () => openDialog(settings));
126
+ settings.className = "consent-action consent-preferences";
127
+ const optOut = button(labels.optOut, () => {
128
+ void controller.restrict({ sale: true, sharing: true, targeted_advertising: true, sensitive_data: false }, locale);
129
+ });
130
+ optOut.className = "consent-action consent-optout";
131
+ const shortcuts = element("div");
132
+ shortcuts.className = "consent-shortcuts";
133
+ shortcuts.append(settings, optOut);
134
+ const dialog = element("dialog");
135
+ dialog.className = "consent-dialog";
136
+ const dialogTitle = element("h2", labels.settings);
137
+ dialogTitle.id = `consent-title-${crypto.randomUUID()}`;
138
+ dialog.setAttribute("aria-labelledby", dialogTitle.id);
139
+ const dialogDescription = element("p");
140
+ const close = button(labels.close, () => closeDialog());
141
+ const fields = element("div");
142
+ fields.className = "consent-categories";
143
+ const inputs = new Map();
144
+ for (const category of ["necessary", "preferences", "analytics", "marketing"]) {
145
+ const label = element("label");
146
+ const input = element("input");
147
+ input.type = "checkbox";
148
+ input.name = category;
149
+ input.checked = category === "necessary";
150
+ input.disabled = category === "necessary";
151
+ label.append(input, document.createTextNode(labels[category] + (category === "necessary" ? ` — ${labels.always}` : "")));
152
+ fields.append(label);
153
+ inputs.set(category, input);
154
+ }
155
+ const inventory = element("div");
156
+ inventory.className = "consent-inventory";
157
+ const regional = element("div");
158
+ regional.className = "consent-regional";
159
+ const privacyFields = element("fieldset");
160
+ privacyFields.className = "consent-categories";
161
+ privacyFields.append(element("legend", labels.privacyRights));
162
+ const restrictionInputs = new Map();
163
+ for (const name of restrictionNames) {
164
+ const label = element("label");
165
+ const input = element("input");
166
+ input.type = "checkbox";
167
+ input.name = `restrict_${name}`;
168
+ restrictionInputs.set(name, input);
169
+ label.append(input, document.createTextNode(labels[name]));
170
+ privacyFields.append(label);
171
+ }
172
+ const signal = element("p");
173
+ signal.setAttribute("role", "status");
174
+ signal.className = "consent-signal";
175
+ const bannerSignal = element("p");
176
+ bannerSignal.className = "consent-signal";
177
+ banner.insertBefore(bannerSignal, actions);
178
+ const rights = element("div");
179
+ rights.className = "consent-rights";
180
+ const save = button(labels.save, () => {
181
+ void controller
182
+ .decide({
183
+ preferences: inputs.get("preferences")?.checked === true,
184
+ analytics: inputs.get("analytics")?.checked === true,
185
+ marketing: inputs.get("marketing")?.checked === true,
186
+ }, locale, {
187
+ sale: restrictionInputs.get("sale")?.checked === true,
188
+ sharing: restrictionInputs.get("sharing")?.checked === true,
189
+ targeted_advertising: restrictionInputs.get("targeted_advertising")?.checked === true,
190
+ sensitive_data: restrictionInputs.get("sensitive_data")?.checked === true,
191
+ })
192
+ .then((saved) => {
193
+ if (saved)
194
+ closeDialog();
195
+ });
196
+ });
197
+ const dialogReject = button(labels.reject, () => {
198
+ void controller.decide({ preferences: false, analytics: false, marketing: false }, locale);
199
+ closeDialog();
200
+ });
201
+ const dialogActions = element("div");
202
+ dialogActions.className = "consent-actions";
203
+ dialogActions.append(save, dialogReject, close);
204
+ // The page status sits behind a modal dialog and is inert there.
205
+ const failure = element("p");
206
+ failure.className = "consent-signal consent-failure";
207
+ failure.setAttribute("role", "alert");
208
+ dialog.append(dialogTitle, dialogDescription, regional, signal, privacyFields, element("p", labels.rightsScope), rights, fields, element("h3", labels.inventory), inventory, failure, dialogActions);
209
+ host.append(banner, shortcuts, status, dialog);
210
+ (options.container ?? document.body).append(host);
211
+ let opener = null;
212
+ let lastPolicy = "";
213
+ function closeDialog() {
214
+ if (dialog.open)
215
+ dialog.close();
216
+ }
217
+ function openDialog(source) {
218
+ // A modal inside the hidden root would leave the whole page inert and invisible.
219
+ if (dialog.open || host.hidden)
220
+ return;
221
+ opener =
222
+ source ?? (document.activeElement instanceof HTMLElement ? document.activeElement : null);
223
+ const state = controller.state;
224
+ for (const category of ["preferences", "analytics", "marketing"]) {
225
+ const input = inputs.get(category);
226
+ if (input)
227
+ input.checked = state.choices[category];
228
+ }
229
+ for (const name of restrictionNames) {
230
+ const input = restrictionInputs.get(name);
231
+ input.checked = state.restrictions[name];
232
+ input.disabled = state.privacy_signals.gpc && name !== "sensitive_data";
233
+ }
234
+ dialog.showModal();
235
+ inputs.get("preferences")?.focus();
236
+ }
237
+ dialog.addEventListener("close", () => {
238
+ if (!opener?.isConnected)
239
+ return;
240
+ // The choice may just have hidden the banner or placeholder which holds the opener.
241
+ (opener.closest("[hidden]") ? settings : opener).focus();
242
+ });
243
+ function render(state) {
244
+ const policy = state.config.policy;
245
+ host.hidden = !state.config.enabled || (policy.services.length === 0 && !policy.regional);
246
+ if (host.hidden)
247
+ closeDialog();
248
+ const notices = regionalNotices(state.config, requestedLocale);
249
+ const notice = notices[0]?.notice;
250
+ if (notice) {
251
+ title.textContent = notice.title;
252
+ description.textContent = notice.description;
253
+ banner.setAttribute("aria-label", notice.title);
254
+ privacy.href = notice.privacy_url;
255
+ dialogDescription.textContent = notice.description;
256
+ host.lang = notices[0]?.locale ?? locale;
257
+ }
258
+ const bannerFocused = banner.contains(document.activeElement);
259
+ banner.hidden = state.decided && !state.error;
260
+ // Hiding the focused control would drop keyboard users back to the start of the page.
261
+ if (bannerFocused && banner.hidden)
262
+ settings.focus();
263
+ accept.disabled = state.pending;
264
+ save.disabled = state.pending;
265
+ status.textContent = state.pending ? labels.pending : state.error ? labels.failed : "";
266
+ failure.textContent = state.error ? labels.failed : "";
267
+ signal.textContent = bannerSignal.textContent = state.privacy_signals.gpc ? labels.gpc : "";
268
+ signal.hidden = bannerSignal.hidden = !state.privacy_signals.gpc;
269
+ for (const name of restrictionNames) {
270
+ const input = restrictionInputs.get(name);
271
+ input.disabled = state.privacy_signals.gpc && name !== "sensitive_data";
272
+ if (input.disabled || !dialog.open)
273
+ input.checked = state.restrictions[name];
274
+ }
275
+ const fingerprint = JSON.stringify([policy, state.config.region]);
276
+ if (lastPolicy === fingerprint)
277
+ return;
278
+ lastPolicy = fingerprint;
279
+ regional.replaceChildren();
280
+ const location = state.config.region?.subdivision ?? state.config.region?.country;
281
+ regional.append(element("p", location ? `${labels.region}: ${location}` : labels.globalStrict));
282
+ for (const extra of notices.slice(1)) {
283
+ const section = element("section");
284
+ section.lang = extra.locale;
285
+ const link = element("a", labels.privacy);
286
+ link.href = extra.notice.privacy_url;
287
+ link.rel = "noopener noreferrer";
288
+ section.append(element("h3", extra.notice.title), element("p", extra.notice.description), link);
289
+ regional.append(section);
290
+ }
291
+ rights.replaceChildren();
292
+ const links = regionalRights(state.config, requestedLocale);
293
+ for (const [url, label] of [
294
+ [links?.request_url, labels.requestRights],
295
+ [links?.appeal_url, labels.appeal],
296
+ ]) {
297
+ if (!url)
298
+ continue;
299
+ const link = element("a", label);
300
+ link.href = url;
301
+ link.rel = "noopener noreferrer";
302
+ rights.append(link);
303
+ }
304
+ inventory.replaceChildren();
305
+ for (const service of policy.services) {
306
+ const section = element("section");
307
+ const heading = element("h4", service.name);
308
+ const body = element("p", service.description);
309
+ const provider = element("p", `${labels.provider}: ${service.provider} · ${labels[service.category]}`);
310
+ const link = element("a", labels.privacy);
311
+ link.href = service.policy_url;
312
+ link.rel = "noopener noreferrer";
313
+ section.append(heading, body, provider, link);
314
+ if (service.processing) {
315
+ const declared = restrictionNames
316
+ .filter((name) => service.processing?.[name])
317
+ .map((name) => ({
318
+ sale: labels.saleProcessing,
319
+ sharing: labels.sharingProcessing,
320
+ targeted_advertising: labels.advertisingProcessing,
321
+ sensitive_data: labels.sensitiveProcessing,
322
+ })[name]);
323
+ if (declared.length)
324
+ section.append(element("p", declared.join(" · ")));
325
+ }
326
+ else if (service.category !== "necessary")
327
+ section.append(element("p", labels.processingUnknown));
328
+ if (service.destination)
329
+ section.append(element("p", `${labels.destination}: ${service.destination}`));
330
+ if (service.storage.length) {
331
+ const list = element("ul");
332
+ for (const item of service.storage)
333
+ list.append(element("li", `${item.name} (${item.type}${item.domain ? `, ${item.domain}` : ""}${item.path ? `, ${item.path}` : ""})`));
334
+ section.append(element("p", labels.storage), list);
335
+ }
336
+ inventory.append(section);
337
+ }
338
+ }
339
+ const unsubscribe = controller.subscribe(render);
340
+ return {
341
+ open: openDialog,
342
+ destroy() {
343
+ closeDialog();
344
+ unsubscribe();
345
+ host.remove();
346
+ },
347
+ };
348
+ }
@@ -0,0 +1,10 @@
1
+ import type { Choices, Policy, PublicConfig } from "./types.js";
2
+ export declare function safeURL(value: unknown, allowPath?: boolean): value is string;
3
+ export declare function validChoices(value: unknown): value is Choices;
4
+ export declare function resolveNoticeLocale(policy: Policy, requested: string): string;
5
+ export declare function validRegionalPolicy(value: unknown): boolean;
6
+ export declare function validRegionSelection(value: unknown): boolean;
7
+ /** Returns a normalized policy. Omitted durations use the shared Go defaults. */
8
+ export declare function parsePolicy(value: unknown): Policy | null;
9
+ export declare function validatePolicy(value: unknown): value is Policy;
10
+ export declare function validateConfig(value: unknown): value is PublicConfig;