@hagicode/hagilight-core 0.18.0 → 0.19.1-dev.185.1.a85e2a8
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/Analytics51LA.astro +19 -3
- package/CookieConsent.astro +402 -0
- package/Footer.astro +31 -5
- package/FooterBrand.astro +23 -3
- package/GoogleAnalytics.astro +17 -2
- package/PostHog.astro +55 -3
- package/PromotoBanner.astro +3 -3
- package/README.md +102 -8
- package/dist/analytics-events.d.ts +15 -0
- package/dist/analytics-events.js +25 -15
- package/dist/consent-copy/de-DE.d.ts +2 -0
- package/dist/consent-copy/de-DE.js +21 -0
- package/dist/consent-copy/en-US.d.ts +2 -0
- package/dist/consent-copy/en-US.js +21 -0
- package/dist/consent-copy/es-ES.d.ts +2 -0
- package/dist/consent-copy/es-ES.js +21 -0
- package/dist/consent-copy/fr-FR.d.ts +2 -0
- package/dist/consent-copy/fr-FR.js +21 -0
- package/dist/consent-copy/index.d.ts +7 -0
- package/dist/consent-copy/index.js +31 -0
- package/dist/consent-copy/ja-JP.d.ts +2 -0
- package/dist/consent-copy/ja-JP.js +21 -0
- package/dist/consent-copy/ko-KR.d.ts +2 -0
- package/dist/consent-copy/ko-KR.js +21 -0
- package/dist/consent-copy/pt-BR.d.ts +2 -0
- package/dist/consent-copy/pt-BR.js +21 -0
- package/dist/consent-copy/ru-RU.d.ts +2 -0
- package/dist/consent-copy/ru-RU.js +21 -0
- package/dist/consent-copy/types.d.ts +22 -0
- package/dist/consent-copy/types.js +1 -0
- package/dist/consent-copy/zh-CN.d.ts +2 -0
- package/dist/consent-copy/zh-CN.js +21 -0
- package/dist/consent-copy/zh-Hant.d.ts +2 -0
- package/dist/consent-copy/zh-Hant.js +21 -0
- package/dist/consent-details.d.ts +29 -0
- package/dist/consent-details.js +41 -0
- package/dist/consent-gate.d.ts +47 -0
- package/dist/consent-gate.js +243 -0
- package/dist/consent-markup.d.ts +33 -0
- package/dist/consent-markup.js +113 -0
- package/dist/consent-mount.d.ts +26 -0
- package/dist/consent-mount.js +81 -0
- package/dist/consent-popup.d.ts +6 -0
- package/dist/consent-popup.js +203 -0
- package/dist/consent.d.ts +65 -0
- package/dist/consent.js +314 -0
- package/dist/entity-definition.d.ts +19 -0
- package/dist/entity-definition.js +23 -0
- package/dist/link-policy.d.ts +7 -2
- package/dist/link-policy.js +8 -1
- package/dist/links.d.ts +12 -4
- package/dist/links.js +16 -10
- package/dist/posthog-events.d.ts +95 -0
- package/dist/posthog-events.js +263 -0
- package/dist/posthog-interactions.d.ts +85 -0
- package/dist/posthog-interactions.js +280 -0
- package/dist/posthog.d.ts +25 -3
- package/dist/posthog.js +64 -6
- package/dist/promoto-analytics.d.ts +45 -0
- package/dist/promoto-analytics.js +92 -0
- package/dist/promoto-banner.js +62 -4
- package/dist/related-sites.json +2 -2
- package/dist/root-transit.d.ts +7 -1
- package/dist/root-transit.js +42 -1
- package/dist/seo.d.ts +30 -1
- package/dist/seo.js +93 -1
- package/dist/site-metadata.d.ts +11 -6
- package/dist/site-metadata.js +21 -8
- package/package.json +42 -1
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The popup's details content as data: the categories, the analytics providers a site enables and the cookie and
|
|
3
|
+
* storage names each one uses. The provider names come from the verified SDK behavior recorded in `consent-gate.ts`
|
|
4
|
+
* and `test/fixtures/consent-sdk-storage.json`. Names are data, not copy, so they are not translated.
|
|
5
|
+
*/
|
|
6
|
+
export type ConsentProvider = 'googleAnalytics' | 'fiftyOneLa' | 'posthog';
|
|
7
|
+
export type StorageKind = 'cookie' | 'localStorage' | 'sessionStorage';
|
|
8
|
+
export interface StorageEntry {
|
|
9
|
+
/** A literal name, or a pattern where `<key>` is the PostHog project key and `<id>` the GA measurement ID without `G-`. */
|
|
10
|
+
name: string;
|
|
11
|
+
kind: StorageKind;
|
|
12
|
+
}
|
|
13
|
+
/** Storage that hagilight and its site write whatever the analytics choice is. */
|
|
14
|
+
export declare const NECESSARY_STORAGE: readonly StorageEntry[];
|
|
15
|
+
/**
|
|
16
|
+
* Storage written by each analytics provider after a grant. 51LA has no entry yet: its cookie and storage names are
|
|
17
|
+
* not verified (task 1.3), so the details never list guessed names for it.
|
|
18
|
+
*/
|
|
19
|
+
export declare const PROVIDER_STORAGE: Readonly<Partial<Record<ConsentProvider, readonly StorageEntry[]>>>;
|
|
20
|
+
export interface ConsentDetails {
|
|
21
|
+
necessary: readonly StorageEntry[];
|
|
22
|
+
analytics: {
|
|
23
|
+
/** Only the providers the site enables; a provider with no verified names is listed with an empty storage list. */
|
|
24
|
+
providers: readonly ConsentProvider[];
|
|
25
|
+
storage: readonly StorageEntry[];
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/** The details for the providers a site enables. Session replay belongs to the providers that record sessions; 51LA records no screen. */
|
|
29
|
+
export declare function consentDetails(enabled: readonly ConsentProvider[]): ConsentDetails;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The popup's details content as data: the categories, the analytics providers a site enables and the cookie and
|
|
3
|
+
* storage names each one uses. The provider names come from the verified SDK behavior recorded in `consent-gate.ts`
|
|
4
|
+
* and `test/fixtures/consent-sdk-storage.json`. Names are data, not copy, so they are not translated.
|
|
5
|
+
*/
|
|
6
|
+
/** Storage that hagilight and its site write whatever the analytics choice is. */
|
|
7
|
+
export const NECESSARY_STORAGE = [
|
|
8
|
+
{ name: 'hagicode_consent', kind: 'cookie' },
|
|
9
|
+
{ name: 'hagicode:consent', kind: 'localStorage' },
|
|
10
|
+
{ name: 'hagicode:site-locale', kind: 'localStorage' },
|
|
11
|
+
{ name: 'starlight-route', kind: 'localStorage' },
|
|
12
|
+
{ name: 'hagicode_locale_monitor', kind: 'cookie' },
|
|
13
|
+
{ name: 'hagicode:locale-monitor', kind: 'localStorage' },
|
|
14
|
+
{ name: 'hagilight-theme', kind: 'localStorage' },
|
|
15
|
+
{ name: 'starlight-theme', kind: 'localStorage' },
|
|
16
|
+
{ name: 'hagilight-content-width', kind: 'localStorage' },
|
|
17
|
+
{ name: 'hagilight:promoto-banner:dismissed-signature', kind: 'localStorage' },
|
|
18
|
+
];
|
|
19
|
+
/**
|
|
20
|
+
* Storage written by each analytics provider after a grant. 51LA has no entry yet: its cookie and storage names are
|
|
21
|
+
* not verified (task 1.3), so the details never list guessed names for it.
|
|
22
|
+
*/
|
|
23
|
+
export const PROVIDER_STORAGE = {
|
|
24
|
+
googleAnalytics: [
|
|
25
|
+
{ name: '_ga', kind: 'cookie' },
|
|
26
|
+
{ name: '_ga_<id>', kind: 'cookie' },
|
|
27
|
+
],
|
|
28
|
+
posthog: [
|
|
29
|
+
{ name: 'ph_<key>_posthog', kind: 'cookie' },
|
|
30
|
+
{ name: 'ph_<key>_posthog', kind: 'localStorage' },
|
|
31
|
+
{ name: '__ph_opt_in_out_<key>', kind: 'localStorage' },
|
|
32
|
+
{ name: 'ph_<key>_session_registered_properties', kind: 'sessionStorage' },
|
|
33
|
+
{ name: 'ph_<key>_primary_window_exists', kind: 'sessionStorage' },
|
|
34
|
+
],
|
|
35
|
+
};
|
|
36
|
+
/** The details for the providers a site enables. Session replay belongs to the providers that record sessions; 51LA records no screen. */
|
|
37
|
+
export function consentDetails(enabled) {
|
|
38
|
+
const providers = enabled.filter((provider, index) => enabled.indexOf(provider) === index);
|
|
39
|
+
const storage = providers.flatMap((provider) => PROVIDER_STORAGE[provider] ?? []);
|
|
40
|
+
return { necessary: NECESSARY_STORAGE, analytics: { providers, storage } };
|
|
41
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type ConsentState } from './consent.js';
|
|
2
|
+
export type GateProvider = 'googleAnalytics' | 'fiftyOneLa' | 'posthog';
|
|
3
|
+
/** The consent reads and subscriptions the gate uses. The page uses the module functions; tests inject a fake. */
|
|
4
|
+
export interface ConsentApi {
|
|
5
|
+
getConsent: () => ConsentState;
|
|
6
|
+
onConsentChange: (listener: (state: ConsentState) => void) => () => void;
|
|
7
|
+
}
|
|
8
|
+
/** The minimal document and window surface the gate touches. Tests pass fakes; the page passes the real globals. */
|
|
9
|
+
export interface GateEnvironment {
|
|
10
|
+
document: Document;
|
|
11
|
+
window: Window;
|
|
12
|
+
/** Reloads the page. Called only when a started provider cannot be stopped in place. */
|
|
13
|
+
reload: () => void;
|
|
14
|
+
}
|
|
15
|
+
export interface GoogleAnalyticsDescriptor {
|
|
16
|
+
measurementId: string;
|
|
17
|
+
}
|
|
18
|
+
export interface FiftyOneLaDescriptor {
|
|
19
|
+
siteId: string;
|
|
20
|
+
}
|
|
21
|
+
export interface PostHogDescriptor {
|
|
22
|
+
apiKey: string;
|
|
23
|
+
/** The unchanged output of `posthogInitScript`, injected inline only after a grant. */
|
|
24
|
+
loader: string;
|
|
25
|
+
}
|
|
26
|
+
export interface ProviderDescriptors {
|
|
27
|
+
googleAnalytics?: GoogleAnalyticsDescriptor;
|
|
28
|
+
fiftyOneLa?: FiftyOneLaDescriptor;
|
|
29
|
+
posthog?: PostHogDescriptor;
|
|
30
|
+
}
|
|
31
|
+
export declare function onPostHogStarted(hook: () => void): void;
|
|
32
|
+
/** Reads the inert descriptors. A descriptor that does not parse or has the wrong shape is ignored. */
|
|
33
|
+
export declare function readDescriptors(doc: Document): ProviderDescriptors;
|
|
34
|
+
export interface ConsentGate {
|
|
35
|
+
/** The providers this document has started, in the order they started. */
|
|
36
|
+
started(): readonly GateProvider[];
|
|
37
|
+
/** Removes the subscription. It does not stop providers that are already running. */
|
|
38
|
+
dispose(): void;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Starts enabled providers once the visitor grants analytics and stops them on withdrawal. A provider starts at most
|
|
42
|
+
* once per document. Nothing is queued while undecided, and the gate never starts a provider while the decision is
|
|
43
|
+
* denied or undecided. Withdrawal stops each started provider, then reloads if any of them cannot stop in place.
|
|
44
|
+
*/
|
|
45
|
+
export declare function installConsentGate(env: GateEnvironment, consent?: ConsentApi): ConsentGate;
|
|
46
|
+
/** Installs the gate once per page, reading the real window and document. A second call returns the first gate. */
|
|
47
|
+
export declare function mountConsentGate(win?: Window, doc?: Document): ConsentGate;
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Consent gate (task 1.1, 1.2, 1.3). The provider table below is filled in as SDK facts are verified; the
|
|
3
|
+
* loader, start and stop logic is added by task 5.1.
|
|
4
|
+
*
|
|
5
|
+
* Verified SDK facts, observed in headless Chromium with the shipped loaders (2026-10-26). Requests to the
|
|
6
|
+
* provider hosts were aborted, so no analytics event left the machine. Fixture: test/fixtures/consent-sdk-storage.json.
|
|
7
|
+
*
|
|
8
|
+
* | Provider | Cookie names | localStorage names | sessionStorage names | Opt-out / clear calls | Stop in place |
|
|
9
|
+
* |---|---|---|---|---|---|
|
|
10
|
+
* | PostHog (`phc_qiVV...PER5`, loader from `posthogInitScript`) | `ph_<key>_posthog` (written after the first `capture` on an opted-in page) | `ph_<key>_posthog`, `__ph_opt_in_out_<key>` (opt-out state) | `ph_<key>_session_registered_properties`, `ph_<key>_primary_window_exists` | `opt_out_capturing()` writes the opt-out state; `opt_in_capturing()` not observed; `clear_opt_in_out_capturing()` removes `__ph_opt_in_out_<key>` only. Opt-out is not a cleanup: `ph_` cookie and storage stay and must be removed by the gate. | Documented: opting out stops all capture, autocapture and session replay on the client. Not observed: the harness never let capture reach the network, so `stopInPlace` stays false until the group-10 browser check (10.2) confirms no request after reject. |
|
|
11
|
+
* | Google Analytics (`G-EN03FMT2Q4`, `gtag.js`) | `_ga`, `_ga_<id>` where `<id>` is the measurement ID without the `G-` prefix (`_ga_EN03FMT2Q4`), both set on the page host after `config` | none | none | `window['ga-disable-<id>'] = true` set before `gtag.js` runs: no cookie and no `collect` request. Set after `config` (the in-place case): `collect` requests are still attempted, so the flag does not stop an initialized page in place. | false, reload on withdrawal |
|
|
12
|
+
* | 51LA (`L6b88a5yK4h2Xnci`, `sdk.51.la/js-sdk-pro.min.js`) | not observed: `sdk.51.la` does not resolve from this machine (DNS) | not observed | not observed | task 1.3 is open: the SDK source could not be fetched here, so no stop or consent API is recorded | always reload (hard-coded) |
|
|
13
|
+
*/
|
|
14
|
+
import { getConsent as readConsent, onConsentChange as subscribeConsent } from './consent.js';
|
|
15
|
+
const moduleConsentApi = { getConsent: readConsent, onConsentChange: subscribeConsent };
|
|
16
|
+
const DESCRIPTOR_SELECTOR = 'script[type="application/json"][data-hagilight-analytics]';
|
|
17
|
+
const PROVIDERS = ['googleAnalytics', 'fiftyOneLa', 'posthog'];
|
|
18
|
+
/** Post-grant hooks run once after PostHog starts, so later listeners install only from the grant. */
|
|
19
|
+
const postGrantHooks = [];
|
|
20
|
+
export function onPostHogStarted(hook) {
|
|
21
|
+
if (typeof hook === 'function')
|
|
22
|
+
postGrantHooks.push(hook);
|
|
23
|
+
}
|
|
24
|
+
/** Reads the inert descriptors. A descriptor that does not parse or has the wrong shape is ignored. */
|
|
25
|
+
export function readDescriptors(doc) {
|
|
26
|
+
const found = {};
|
|
27
|
+
for (const element of Array.from(doc.querySelectorAll(DESCRIPTOR_SELECTOR))) {
|
|
28
|
+
const provider = element.getAttribute('data-hagilight-analytics');
|
|
29
|
+
if (!provider || !PROVIDERS.includes(provider))
|
|
30
|
+
continue;
|
|
31
|
+
try {
|
|
32
|
+
found[provider] = JSON.parse(element.textContent ?? '');
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// Ignore a malformed descriptor: that provider simply does not start.
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const ga = found.googleAnalytics;
|
|
39
|
+
const la = found.fiftyOneLa;
|
|
40
|
+
const ph = found.posthog;
|
|
41
|
+
return {
|
|
42
|
+
...(typeof ga?.measurementId === 'string' && ga.measurementId ? { googleAnalytics: { measurementId: ga.measurementId } } : {}),
|
|
43
|
+
...(typeof la?.siteId === 'string' && la.siteId ? { fiftyOneLa: { siteId: la.siteId } } : {}),
|
|
44
|
+
...(typeof ph?.apiKey === 'string' && typeof ph.loader === 'string' ? { posthog: { apiKey: ph.apiKey, loader: ph.loader } } : {}),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function injectScript(env, attributes, onLoad) {
|
|
48
|
+
const script = env.document.createElement('script');
|
|
49
|
+
for (const [name, value] of Object.entries(attributes))
|
|
50
|
+
script.setAttribute(name, value);
|
|
51
|
+
if (onLoad)
|
|
52
|
+
script.addEventListener('load', onLoad);
|
|
53
|
+
(env.document.head ?? env.document.body).appendChild(script);
|
|
54
|
+
return script;
|
|
55
|
+
}
|
|
56
|
+
function injectInline(env, code) {
|
|
57
|
+
const script = env.document.createElement('script');
|
|
58
|
+
script.textContent = code;
|
|
59
|
+
(env.document.head ?? env.document.body).appendChild(script);
|
|
60
|
+
}
|
|
61
|
+
/** Cookie names of one provider are removed on the page host, with the same path the SDK sets. */
|
|
62
|
+
function expireCookie(env, name) {
|
|
63
|
+
try {
|
|
64
|
+
env.document.cookie = `${name}=; Path=/; Max-Age=0`;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
// Cookies blocked: nothing was written either.
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function cookieNames(env) {
|
|
71
|
+
try {
|
|
72
|
+
return env.document.cookie.split(';').map((pair) => pair.split('=')[0].trim()).filter(Boolean);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return [];
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function removePrefixedStorage(storage, prefix) {
|
|
79
|
+
try {
|
|
80
|
+
if (!storage)
|
|
81
|
+
return;
|
|
82
|
+
const keys = [];
|
|
83
|
+
for (let index = 0; index < storage.length; index += 1) {
|
|
84
|
+
const key = storage.key(index);
|
|
85
|
+
if (key?.startsWith(prefix))
|
|
86
|
+
keys.push(key);
|
|
87
|
+
}
|
|
88
|
+
for (const key of keys)
|
|
89
|
+
storage.removeItem(key);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
// Storage blocked: nothing to clean.
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function safeStorage(env, kind) {
|
|
96
|
+
try {
|
|
97
|
+
return env.window[kind];
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const TABLE = {
|
|
104
|
+
googleAnalytics: {
|
|
105
|
+
stopInPlace: false,
|
|
106
|
+
start(env, descriptors) {
|
|
107
|
+
const id = descriptors.googleAnalytics?.measurementId;
|
|
108
|
+
if (!id)
|
|
109
|
+
return;
|
|
110
|
+
injectScript(env, { async: '', src: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(id)}` }, () => {
|
|
111
|
+
const win = env.window;
|
|
112
|
+
win.dataLayer = win.dataLayer ?? [];
|
|
113
|
+
win.gtag = function gtag(...args) {
|
|
114
|
+
win.dataLayer.push(args);
|
|
115
|
+
};
|
|
116
|
+
win.gtag('js', new Date());
|
|
117
|
+
win.gtag('config', id);
|
|
118
|
+
});
|
|
119
|
+
},
|
|
120
|
+
stop(env, descriptors) {
|
|
121
|
+
const id = descriptors.googleAnalytics?.measurementId;
|
|
122
|
+
if (!id)
|
|
123
|
+
return;
|
|
124
|
+
env.window[`ga-disable-${id}`] = true;
|
|
125
|
+
const bare = id.replace(/^G-/u, '');
|
|
126
|
+
for (const name of cookieNames(env)) {
|
|
127
|
+
if (name === '_ga' || name === `_ga_${bare}`)
|
|
128
|
+
expireCookie(env, name);
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
fiftyOneLa: {
|
|
133
|
+
stopInPlace: false,
|
|
134
|
+
start(env, descriptors) {
|
|
135
|
+
const siteId = descriptors.fiftyOneLa?.siteId;
|
|
136
|
+
if (!siteId)
|
|
137
|
+
return;
|
|
138
|
+
injectScript(env, { charset: 'UTF-8', id: 'LA_COLLECT', src: 'https://sdk.51.la/js-sdk-pro.min.js' }, () => {
|
|
139
|
+
const la = env.window.LA;
|
|
140
|
+
// No screenRecord: 51LA records no screen and has no session replay.
|
|
141
|
+
la?.init({ id: siteId, ck: siteId, autoTrack: true, hashMode: true });
|
|
142
|
+
});
|
|
143
|
+
},
|
|
144
|
+
stop() {
|
|
145
|
+
// No stop API is known for 51LA. The gate reloads after the denial is persisted, and never starts it while denied.
|
|
146
|
+
},
|
|
147
|
+
},
|
|
148
|
+
posthog: {
|
|
149
|
+
stopInPlace: false,
|
|
150
|
+
start(env, descriptors) {
|
|
151
|
+
const ph = descriptors.posthog;
|
|
152
|
+
if (!ph)
|
|
153
|
+
return;
|
|
154
|
+
// A previous opt-out would keep capture off after the grant, so the stored opt-out state is cleared first.
|
|
155
|
+
removeStorageKey(safeStorage(env, 'localStorage'), `__ph_opt_in_out_${ph.apiKey}`);
|
|
156
|
+
injectInline(env, ph.loader);
|
|
157
|
+
for (const hook of postGrantHooks) {
|
|
158
|
+
try {
|
|
159
|
+
hook();
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
// A failing hook must not stop the others.
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
},
|
|
166
|
+
stop(env) {
|
|
167
|
+
try {
|
|
168
|
+
const posthog = env.window.posthog;
|
|
169
|
+
posthog?.opt_out_capturing?.();
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// The SDK may not have loaded.
|
|
173
|
+
}
|
|
174
|
+
for (const name of cookieNames(env)) {
|
|
175
|
+
if (name.startsWith('ph_'))
|
|
176
|
+
expireCookie(env, name);
|
|
177
|
+
}
|
|
178
|
+
removePrefixedStorage(safeStorage(env, 'localStorage'), 'ph_');
|
|
179
|
+
removePrefixedStorage(safeStorage(env, 'sessionStorage'), 'ph_');
|
|
180
|
+
},
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
function removeStorageKey(storage, key) {
|
|
184
|
+
try {
|
|
185
|
+
storage?.removeItem(key);
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
// Storage blocked.
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Starts enabled providers once the visitor grants analytics and stops them on withdrawal. A provider starts at most
|
|
193
|
+
* once per document. Nothing is queued while undecided, and the gate never starts a provider while the decision is
|
|
194
|
+
* denied or undecided. Withdrawal stops each started provider, then reloads if any of them cannot stop in place.
|
|
195
|
+
*/
|
|
196
|
+
export function installConsentGate(env, consent = moduleConsentApi) {
|
|
197
|
+
/** Providers running now. Withdrawal empties it. */
|
|
198
|
+
const startedOrder = [];
|
|
199
|
+
/** Providers ever started in this document. A provider starts at most once per document, even after a withdrawal. */
|
|
200
|
+
const everStarted = new Set();
|
|
201
|
+
let descriptors = readDescriptors(env.document);
|
|
202
|
+
const startAll = () => {
|
|
203
|
+
for (const provider of PROVIDERS) {
|
|
204
|
+
if (everStarted.has(provider) || !descriptors[provider])
|
|
205
|
+
continue;
|
|
206
|
+
everStarted.add(provider);
|
|
207
|
+
startedOrder.push(provider);
|
|
208
|
+
TABLE[provider].start(env, descriptors);
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
const stopAll = () => {
|
|
212
|
+
let needsReload = false;
|
|
213
|
+
for (const provider of startedOrder) {
|
|
214
|
+
TABLE[provider].stop(env, descriptors);
|
|
215
|
+
if (!TABLE[provider].stopInPlace)
|
|
216
|
+
needsReload = true;
|
|
217
|
+
}
|
|
218
|
+
startedOrder.length = 0;
|
|
219
|
+
if (needsReload)
|
|
220
|
+
env.reload();
|
|
221
|
+
};
|
|
222
|
+
const apply = (state) => {
|
|
223
|
+
if (state.analytics === 'granted')
|
|
224
|
+
startAll();
|
|
225
|
+
else if (state.analytics === 'denied' && startedOrder.length > 0)
|
|
226
|
+
stopAll();
|
|
227
|
+
};
|
|
228
|
+
const unsubscribe = consent.onConsentChange(apply);
|
|
229
|
+
apply(consent.getConsent());
|
|
230
|
+
return {
|
|
231
|
+
started: () => [...startedOrder],
|
|
232
|
+
dispose: unsubscribe,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
/** Installs the gate once per page, reading the real window and document. A second call returns the first gate. */
|
|
236
|
+
export function mountConsentGate(win = window, doc = document) {
|
|
237
|
+
const holder = win;
|
|
238
|
+
if (holder.__hagilightConsentGate)
|
|
239
|
+
return holder.__hagilightConsentGate;
|
|
240
|
+
const gate = installConsentGate({ window: win, document: doc, reload: () => win.location.reload() });
|
|
241
|
+
holder.__hagilightConsentGate = gate;
|
|
242
|
+
return gate;
|
|
243
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type ConsentProvider } from './consent-details.js';
|
|
2
|
+
export declare const CONSENT_PROVIDERS: readonly ConsentProvider[];
|
|
3
|
+
export interface ConsentPopupOptions {
|
|
4
|
+
/** The page locale. An unsupported value renders `en-US`. */
|
|
5
|
+
locale?: string;
|
|
6
|
+
/** The analytics providers the site enables. Their storage names appear in the details. */
|
|
7
|
+
providers: readonly ConsentProvider[];
|
|
8
|
+
/** An absolute HTTP(S) URL or a site-relative path. Omitted means no privacy link. */
|
|
9
|
+
privacyUrl?: string;
|
|
10
|
+
/** Defaults to `1`. Changing it asks every visitor again. */
|
|
11
|
+
policyVersion?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface ResolvedConsentPopupOptions {
|
|
14
|
+
locale: string;
|
|
15
|
+
providers: readonly ConsentProvider[];
|
|
16
|
+
privacyUrl: string | undefined;
|
|
17
|
+
policyVersion: string;
|
|
18
|
+
}
|
|
19
|
+
/** Throws a TypeError that names the option when the value is not an absolute HTTP(S) URL or a site-relative path. */
|
|
20
|
+
export declare function validatePrivacyUrl(value: unknown): string | undefined;
|
|
21
|
+
/** Throws a TypeError that names the option when the policy version is not 1 to 32 safe characters. */
|
|
22
|
+
export declare function validatePolicyVersion(value: unknown): string;
|
|
23
|
+
export declare function resolveConsentPopupOptions(options: ConsentPopupOptions): ResolvedConsentPopupOptions;
|
|
24
|
+
export declare function escapeHtml(value: string): string;
|
|
25
|
+
/**
|
|
26
|
+
* The config descriptor for `<script type="application/json" id="hagilight-consent-config">`. It holds only the policy
|
|
27
|
+
* version, the privacy URL, the enabled providers and the locale. `<` is escaped so the JSON cannot close the script.
|
|
28
|
+
*/
|
|
29
|
+
export declare function consentDescriptor(options: ConsentPopupOptions): string;
|
|
30
|
+
/** The ID of the descriptor script, so the popup and the gate can read the same element. */
|
|
31
|
+
export declare const CONSENT_DESCRIPTOR_ID = "hagilight-consent-config";
|
|
32
|
+
/** The popup's HTML: a hidden, labelled, non-modal region with two equal actions and an expandable details section. */
|
|
33
|
+
export declare function renderConsentMarkup(options: ConsentPopupOptions): string;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared popup markup for the consent popup (`CookieConsent.astro` and the Docusaurus client). It is a string, so the
|
|
3
|
+
* same markup renders in both frameworks. The DOM wiring lives in `consent-popup.ts`.
|
|
4
|
+
*/
|
|
5
|
+
import { resolveConsentCopy } from './consent-copy/index.js';
|
|
6
|
+
import { consentDetails } from './consent-details.js';
|
|
7
|
+
import { CONSENT_CONFIG_ID, DEFAULT_POLICY_VERSION } from './consent.js';
|
|
8
|
+
import { DEFAULT_LOCALE, SITE_LOCALE_CODES } from './root-transit-locale.js';
|
|
9
|
+
export const CONSENT_PROVIDERS = ['googleAnalytics', 'posthog', 'fiftyOneLa'];
|
|
10
|
+
/** Brand names stay as written in every locale. */
|
|
11
|
+
const PROVIDER_LABEL = {
|
|
12
|
+
googleAnalytics: 'Google Analytics',
|
|
13
|
+
posthog: 'PostHog',
|
|
14
|
+
fiftyOneLa: '51LA',
|
|
15
|
+
};
|
|
16
|
+
const POLICY = /^[A-Za-z0-9._-]{1,32}$/u;
|
|
17
|
+
/** Throws a TypeError that names the option when the value is not an absolute HTTP(S) URL or a site-relative path. */
|
|
18
|
+
export function validatePrivacyUrl(value) {
|
|
19
|
+
if (value === undefined || value === '')
|
|
20
|
+
return undefined;
|
|
21
|
+
if (typeof value !== 'string')
|
|
22
|
+
throw new TypeError('analytics.consent.privacyUrl must be a string.');
|
|
23
|
+
const trimmed = value.trim();
|
|
24
|
+
if (/^https?:\/\/[^\s]+$/iu.test(trimmed)) {
|
|
25
|
+
try {
|
|
26
|
+
new URL(trimmed);
|
|
27
|
+
return trimmed;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
throw new TypeError(`analytics.consent.privacyUrl is not a valid URL: ${trimmed}`);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (trimmed.startsWith('/') && !trimmed.startsWith('//') && !/\s/u.test(trimmed))
|
|
34
|
+
return trimmed;
|
|
35
|
+
throw new TypeError('analytics.consent.privacyUrl must be an absolute http(s) URL or a site-relative path starting with "/".');
|
|
36
|
+
}
|
|
37
|
+
/** Throws a TypeError that names the option when the policy version is not 1 to 32 safe characters. */
|
|
38
|
+
export function validatePolicyVersion(value) {
|
|
39
|
+
if (value === undefined)
|
|
40
|
+
return DEFAULT_POLICY_VERSION;
|
|
41
|
+
if (typeof value !== 'string' || !POLICY.test(value)) {
|
|
42
|
+
throw new TypeError('analytics.consent.policyVersion must be 1 to 32 letters, digits, dots, underscores or hyphens.');
|
|
43
|
+
}
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
/** The locale code the popup renders: the page locale when it is in `SITE_LOCALES`, otherwise `en-US`. */
|
|
47
|
+
function effectiveLocale(locale) {
|
|
48
|
+
return typeof locale === 'string' && SITE_LOCALE_CODES.includes(locale) ? locale : DEFAULT_LOCALE;
|
|
49
|
+
}
|
|
50
|
+
export function resolveConsentPopupOptions(options) {
|
|
51
|
+
const providers = options.providers.filter((provider, index, all) => all.indexOf(provider) === index);
|
|
52
|
+
return {
|
|
53
|
+
locale: effectiveLocale(options.locale),
|
|
54
|
+
providers,
|
|
55
|
+
privacyUrl: validatePrivacyUrl(options.privacyUrl),
|
|
56
|
+
policyVersion: validatePolicyVersion(options.policyVersion),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
export function escapeHtml(value) {
|
|
60
|
+
return value
|
|
61
|
+
.replace(/&/gu, '&')
|
|
62
|
+
.replace(/</gu, '<')
|
|
63
|
+
.replace(/>/gu, '>')
|
|
64
|
+
.replace(/"/gu, '"')
|
|
65
|
+
.replace(/'/gu, ''');
|
|
66
|
+
}
|
|
67
|
+
function storageList(entries) {
|
|
68
|
+
return entries.map((entry) => `<li><code>${escapeHtml(entry.name)}</code> <span>${escapeHtml(entry.kind)}</span></li>`).join('');
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The config descriptor for `<script type="application/json" id="hagilight-consent-config">`. It holds only the policy
|
|
72
|
+
* version, the privacy URL, the enabled providers and the locale. `<` is escaped so the JSON cannot close the script.
|
|
73
|
+
*/
|
|
74
|
+
export function consentDescriptor(options) {
|
|
75
|
+
const resolved = resolveConsentPopupOptions(options);
|
|
76
|
+
const payload = {
|
|
77
|
+
policyVersion: resolved.policyVersion,
|
|
78
|
+
privacyUrl: resolved.privacyUrl ?? null,
|
|
79
|
+
providers: resolved.providers,
|
|
80
|
+
locale: resolved.locale,
|
|
81
|
+
};
|
|
82
|
+
return JSON.stringify(payload).replace(/</gu, '\\u003c');
|
|
83
|
+
}
|
|
84
|
+
/** The ID of the descriptor script, so the popup and the gate can read the same element. */
|
|
85
|
+
export const CONSENT_DESCRIPTOR_ID = CONSENT_CONFIG_ID;
|
|
86
|
+
/** The popup's HTML: a hidden, labelled, non-modal region with two equal actions and an expandable details section. */
|
|
87
|
+
export function renderConsentMarkup(options) {
|
|
88
|
+
const resolved = resolveConsentPopupOptions(options);
|
|
89
|
+
const copy = resolveConsentCopy(resolved.locale);
|
|
90
|
+
const details = consentDetails(resolved.providers);
|
|
91
|
+
const providerLabels = details.analytics.providers.map((provider) => PROVIDER_LABEL[provider]).join(', ');
|
|
92
|
+
const privacy = resolved.privacyUrl
|
|
93
|
+
? `<p class="hagilight-consent__privacy"><a href="${escapeHtml(resolved.privacyUrl)}">${escapeHtml(copy.privacyLink)}</a></p>`
|
|
94
|
+
: '';
|
|
95
|
+
return [
|
|
96
|
+
`<section class="hagilight-consent" data-hagilight-consent data-state="undecided" role="region" aria-labelledby="hagilight-consent-title" hidden>`,
|
|
97
|
+
`<h2 class="hagilight-consent__title" id="hagilight-consent-title">${escapeHtml(copy.title)}</h2>`,
|
|
98
|
+
`<p class="hagilight-consent__intro">${escapeHtml(copy.intro)}</p>`,
|
|
99
|
+
`<p class="hagilight-consent__choice" data-consent-choice data-choice-granted="${escapeHtml(copy.choiceAccepted)}" data-choice-denied="${escapeHtml(copy.choiceRejected)}" data-choice-undecided="${escapeHtml(copy.choiceUndecided)}">${escapeHtml(copy.choiceLabel)}: <span data-consent-choice-value>${escapeHtml(copy.choiceUndecided)}</span></p>`,
|
|
100
|
+
`<div class="hagilight-consent__actions">`,
|
|
101
|
+
`<button type="button" class="hagilight-consent__button" data-consent-accept>${escapeHtml(copy.accept)}</button>`,
|
|
102
|
+
`<button type="button" class="hagilight-consent__button" data-consent-reject>${escapeHtml(copy.reject)}</button>`,
|
|
103
|
+
`</div>`,
|
|
104
|
+
`<button type="button" class="hagilight-consent__toggle" data-consent-toggle aria-expanded="false" aria-controls="hagilight-consent-details">${escapeHtml(copy.details)}</button>`,
|
|
105
|
+
`<div class="hagilight-consent__details" id="hagilight-consent-details" data-consent-details hidden>`,
|
|
106
|
+
`<section class="hagilight-consent__category hagilight-consent__category--necessary"><h3>${escapeHtml(copy.necessaryTitle)}</h3><p>${escapeHtml(copy.necessaryBody)}</p><ul>${storageList(details.necessary)}</ul></section>`,
|
|
107
|
+
`<section class="hagilight-consent__category hagilight-consent__category--analytics"><h3>${escapeHtml(copy.analyticsTitle)}</h3><p>${escapeHtml(copy.analyticsBody)}${providerLabels ? ` (${escapeHtml(providerLabels)})` : ''}</p><ul>${storageList(details.analytics.storage)}</ul></section>`,
|
|
108
|
+
`<p class="hagilight-consent__withdraw">${escapeHtml(copy.withdraw)}</p>`,
|
|
109
|
+
privacy,
|
|
110
|
+
`</div>`,
|
|
111
|
+
`</section>`,
|
|
112
|
+
].join('');
|
|
113
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Page-level consent wiring shared by the Docusaurus client and the plain-Astro integration. It reads the popup's
|
|
3
|
+
* config descriptor, places the popup markup, installs PostHog's click sink only after a grant, and mounts the gate.
|
|
4
|
+
*/
|
|
5
|
+
import { type ConsentPopupOptions } from './consent-markup.js';
|
|
6
|
+
/** Reads the head's config descriptor. A missing or malformed descriptor means consent is not mounted. */
|
|
7
|
+
export declare function readConsentConfig(doc: Document): ConsentPopupOptions | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* Mounts the popup and the gate for a page whose head carries the consent descriptors. The PostHog click sink
|
|
10
|
+
* installs from the grant, never at load. Nothing here throws into the page: with no readable config there is no
|
|
11
|
+
* popup, and every provider stays off.
|
|
12
|
+
*/
|
|
13
|
+
export declare function mountConsent(doc?: Document, win?: Window): void;
|
|
14
|
+
export interface ConsentHeadInput {
|
|
15
|
+
/** The PostHog loader, carried as inert JSON data. Omit when PostHog is not enabled. */
|
|
16
|
+
posthog?: {
|
|
17
|
+
apiKey: string;
|
|
18
|
+
loader: string;
|
|
19
|
+
};
|
|
20
|
+
config: ConsentPopupOptions;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* An inline head script that inserts the inert descriptors as markup. It runs no provider code: the descriptors are
|
|
24
|
+
* `application/json` elements, and the gate reads them after a grant. Used by integrations that inject PostHog.
|
|
25
|
+
*/
|
|
26
|
+
export declare function consentHeadScript(input: ConsentHeadInput): string;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Page-level consent wiring shared by the Docusaurus client and the plain-Astro integration. It reads the popup's
|
|
3
|
+
* config descriptor, places the popup markup, installs PostHog's click sink only after a grant, and mounts the gate.
|
|
4
|
+
*/
|
|
5
|
+
import { consentDescriptor, CONSENT_DESCRIPTOR_ID, renderConsentMarkup } from './consent-markup.js';
|
|
6
|
+
import { mountConsentGate, onPostHogStarted } from './consent-gate.js';
|
|
7
|
+
import { mountConsentPopup } from './consent-popup.js';
|
|
8
|
+
import { installPostHogClickTracking } from './posthog-events.js';
|
|
9
|
+
import { installPostHogInteractions } from './posthog-interactions.js';
|
|
10
|
+
/** Reads the head's config descriptor. A missing or malformed descriptor means consent is not mounted. */
|
|
11
|
+
export function readConsentConfig(doc) {
|
|
12
|
+
try {
|
|
13
|
+
const text = doc.getElementById(CONSENT_DESCRIPTOR_ID)?.textContent;
|
|
14
|
+
if (!text)
|
|
15
|
+
return undefined;
|
|
16
|
+
const parsed = JSON.parse(text);
|
|
17
|
+
if (!Array.isArray(parsed.providers))
|
|
18
|
+
return undefined;
|
|
19
|
+
return {
|
|
20
|
+
providers: parsed.providers,
|
|
21
|
+
privacyUrl: typeof parsed.privacyUrl === 'string' ? parsed.privacyUrl : undefined,
|
|
22
|
+
policyVersion: typeof parsed.policyVersion === 'string' ? parsed.policyVersion : undefined,
|
|
23
|
+
locale: doc.documentElement.lang,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Mounts the popup and the gate for a page whose head carries the consent descriptors. The PostHog click sink
|
|
32
|
+
* installs from the grant, never at load. Nothing here throws into the page: with no readable config there is no
|
|
33
|
+
* popup, and every provider stays off.
|
|
34
|
+
*/
|
|
35
|
+
export function mountConsent(doc = document, win = window) {
|
|
36
|
+
try {
|
|
37
|
+
const config = readConsentConfig(doc);
|
|
38
|
+
if (!config)
|
|
39
|
+
return;
|
|
40
|
+
if (!doc.querySelector('[data-hagilight-consent]')) {
|
|
41
|
+
doc.body.insertAdjacentHTML('beforeend', renderConsentMarkup(config));
|
|
42
|
+
}
|
|
43
|
+
onPostHogStarted(() => {
|
|
44
|
+
installPostHogClickTracking(doc);
|
|
45
|
+
// The interaction observers wait for the grant too; they read the page only after PostHog may start.
|
|
46
|
+
installPostHogInteractions(doc);
|
|
47
|
+
});
|
|
48
|
+
mountConsentGate(win, doc);
|
|
49
|
+
mountConsentPopup(doc);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// Consent setup must never break the page; with no popup, no provider loads.
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* An inline head script that inserts the inert descriptors as markup. It runs no provider code: the descriptors are
|
|
57
|
+
* `application/json` elements, and the gate reads them after a grant. Used by integrations that inject PostHog.
|
|
58
|
+
*/
|
|
59
|
+
export function consentHeadScript(input) {
|
|
60
|
+
const escape = (text) => text.replace(/</gu, '\\u003c');
|
|
61
|
+
const parts = [];
|
|
62
|
+
if (input.posthog) {
|
|
63
|
+
const payload = escape(JSON.stringify({ apiKey: input.posthog.apiKey, loader: input.posthog.loader }));
|
|
64
|
+
parts.push(`<script type="application/json" data-hagilight-analytics="posthog">${payload}</script>`);
|
|
65
|
+
}
|
|
66
|
+
parts.push(`<script type="application/json" id="${CONSENT_DESCRIPTOR_ID}">${consentDescriptor(input.config)}</script>`);
|
|
67
|
+
return `(function(){document.head.insertAdjacentHTML('beforeend', ${singleQuoted(parts.join(''))});})();`;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* A single-quoted JavaScript string literal. Double quotes stay as written, so the descriptor's
|
|
71
|
+
* `data-hagilight-analytics="posthog"` marker is still visible in the built HTML that detection reads.
|
|
72
|
+
*/
|
|
73
|
+
function singleQuoted(text) {
|
|
74
|
+
const body = text
|
|
75
|
+
.replace(/\\/gu, '\\\\')
|
|
76
|
+
.replace(/'/gu, "\\'")
|
|
77
|
+
.replace(/\r/gu, '\\r')
|
|
78
|
+
.replace(/\n/gu, '\\n')
|
|
79
|
+
.replace(/</gu, '\\u003c');
|
|
80
|
+
return `'${body}'`;
|
|
81
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare const CONSENT_CLEARANCE_PROPERTY = "--hagilight-consent-clearance";
|
|
2
|
+
/**
|
|
3
|
+
* Mounts the popup inside `root` (the `[data-hagilight-consent]` section). Returns a function that removes the listeners.
|
|
4
|
+
* With no panel, or where the visitor already decided or consent is not required, the panel stays hidden.
|
|
5
|
+
*/
|
|
6
|
+
export declare function mountConsentPopup(root?: ParentNode): () => void;
|