Compare commits

...
2 Commits
Author SHA1 Message Date
radoslaw.smolinski a92fc02cdf 1.7.8 2026-10-12 17:32:41 +02:00
radoslaw.smolinski 7aebe24236 Added not-found support for sitesettings 2026-10-12 17:32:31 +02:00
53 changed files with 838 additions and 96 deletions
+3 -2
View File
@@ -1,6 +1,7 @@
import type { Field } from 'payload';
/**
* Analytics configuration — GA4 measurement ID and GTM container ID.
* IDs are public (exposed client-side), so no read restriction needed.
* Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no
* read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only
* after the matching consent category is granted (see modules/analytics).
*/
export declare const analyticsFields: Field[];
+37 -4
View File
@@ -1,12 +1,13 @@
/**
* Analytics configuration — GA4 measurement ID and GTM container ID.
* IDs are public (exposed client-side), so no read restriction needed.
* Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no
* read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only
* after the matching consent category is granted (see modules/analytics).
*/ export const analyticsFields = [
{
name: 'ga4MeasurementId',
type: 'text',
admin: {
description: 'Google Analytics 4 Measurement ID.',
description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)',
placeholder: 'G-XXXXXXXXXX'
}
},
@@ -14,9 +15,41 @@
name: 'gtmContainerId',
type: 'text',
admin: {
description: 'Google Tag Manager container ID.',
description: 'Google Tag Manager container ID. (Google — Consent Mode)',
placeholder: 'GTM-XXXXXXX'
}
},
{
name: 'metaPixelId',
type: 'text',
admin: {
description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.',
placeholder: '1234567890123456'
}
},
{
name: 'clarityProjectId',
type: 'text',
admin: {
description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.',
placeholder: 'abcdefghij'
}
},
{
name: 'linkedInPartnerId',
type: 'text',
admin: {
description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.',
placeholder: '1234567'
}
},
{
name: 'tiktokPixelId',
type: 'text',
admin: {
description: 'TikTok Pixel ID. Loads only after MARKETING consent.',
placeholder: 'CXXXXXXXXXXXXXXXXXXX'
}
}
];
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/analytics.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Analytics configuration — GA4 measurement ID and GTM container ID.\n * IDs are public (exposed client-side), so no read restriction needed.\n */\nexport const analyticsFields: Field[] = [\n {\n name: 'ga4MeasurementId',\n type: 'text',\n admin: {\n description: 'Google Analytics 4 Measurement ID.',\n placeholder: 'G-XXXXXXXXXX',\n },\n },\n {\n name: 'gtmContainerId',\n type: 'text',\n admin: {\n description: 'Google Tag Manager container ID.',\n placeholder: 'GTM-XXXXXXX',\n },\n },\n]\n"],"names":["analyticsFields","name","type","admin","description","placeholder"],"mappings":"AAEA;;;CAGC,GACD,OAAO,MAAMA,kBAA2B;IACtC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;CACD,CAAA"}
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/analytics.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no\n * read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only\n * after the matching consent category is granted (see modules/analytics).\n */\nexport const analyticsFields: Field[] = [\n {\n name: 'ga4MeasurementId',\n type: 'text',\n admin: {\n description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)',\n placeholder: 'G-XXXXXXXXXX',\n },\n },\n {\n name: 'gtmContainerId',\n type: 'text',\n admin: {\n description: 'Google Tag Manager container ID. (Google — Consent Mode)',\n placeholder: 'GTM-XXXXXXX',\n },\n },\n {\n name: 'metaPixelId',\n type: 'text',\n admin: {\n description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.',\n placeholder: '1234567890123456',\n },\n },\n {\n name: 'clarityProjectId',\n type: 'text',\n admin: {\n description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.',\n placeholder: 'abcdefghij',\n },\n },\n {\n name: 'linkedInPartnerId',\n type: 'text',\n admin: {\n description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.',\n placeholder: '1234567',\n },\n },\n {\n name: 'tiktokPixelId',\n type: 'text',\n admin: {\n description: 'TikTok Pixel ID. Loads only after MARKETING consent.',\n placeholder: 'CXXXXXXXXXXXXXXXXXXX',\n },\n },\n]\n"],"names":["analyticsFields","name","type","admin","description","placeholder"],"mappings":"AAEA;;;;CAIC,GACD,OAAO,MAAMA,kBAA2B;IACtC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;CACD,CAAA"}
+1 -1
View File
@@ -7,7 +7,7 @@ export { getAnalyticsConfig } from './modules/analytics/index.js';
export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, DEFAULT_CONSENT, getConsentTexts, parseConsent, REJECT_ALL_CONSENT, serializeConsent, setDefaultConsent, updateConsent, } from './modules/consent/index.js';
export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js';
export type { ContentCollectionOption, ContentOption, ResolvedRoute, } from './modules/content/index.js';
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveRedirect, resolveRoute, searchContent, } from './modules/content/index.js';
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent, } from './modules/content/index.js';
export type { ArchiveEntries } from './modules/content/index.js';
export type { SearchResult } from './modules/content/index.js';
export { graphAdapter } from './modules/email/graphAdapter.js';
+1 -1
View File
@@ -2,7 +2,7 @@ export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSe
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js';
export { getAnalyticsConfig } from './modules/analytics/index.js';
export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, DEFAULT_CONSENT, getConsentTexts, parseConsent, REJECT_ALL_CONSENT, serializeConsent, setDefaultConsent, updateConsent } from './modules/consent/index.js';
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveRedirect, resolveRoute, searchContent } from './modules/content/index.js';
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent } from './modules/content/index.js';
export { graphAdapter } from './modules/email/graphAdapter.js';
export { mailAdapter } from './modules/email/mailAdapter.js';
// Imported straight from the file, NOT from ./modules/email/index.js — that
+1 -1
View File
File diff suppressed because one or more lines are too long
+12 -9
View File
@@ -5,15 +5,18 @@ declare global {
}
}
/**
* Loads Google Analytics — GTM if a container ID is set, otherwise GA4 gtag.
* Loads every configured analytics / marketing tag, each respecting consent:
*
* Consent Mode is initialised to the visitor's stored consent BEFORE the tag
* loads (via setDefaultConsent from the consent module), so tags respect the
* choice from the first hit; useConsent sends an update the moment the visitor
* decides. IDs are public and come from SiteIntegrations, passed in as props
* (the client project reads them server-side).
* - **Google (GA4 / GTM)** — loaded immediately with Consent Mode: the visitor's
* stored choice is set as the default BEFORE the tag loads, and useConsent
* pushes an update the moment they decide. GTM wins if both IDs are set.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — these vendors have
* no Consent Mode, so they load ONLY after the matching category is granted
* (marketing for Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to
* the consent banner: accept → the tag loads immediately, no reload.
*
* Renders nothing — it only injects the scripts. Mount once, high in the tree
* (e.g. root layout), inside ConsentProvider.
* All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed
* in as props. Renders nothing. Mount once, high in the tree, INSIDE
* <ConsentProvider> (required — it reads live consent state).
*/
export declare function Analytics({ ga4MeasurementId, gtmContainerId }: AnalyticsConfig): null;
export declare function Analytics(props: AnalyticsConfig): null;
+44 -13
View File
@@ -1,7 +1,9 @@
'use client';
import { useEffect } from 'react';
import { useConsentContext } from '../consent/client.js';
import { gtag } from '../consent/googleConsent.js';
import { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js';
import { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js';
const GTM_SCRIPT = (id)=>`https://www.googletagmanager.com/gtm.js?id=${id}`;
const GA4_SCRIPT = (id)=>`https://www.googletagmanager.com/gtag/js?id=${id}`;
/** Reads the current consent state from cookie, or defaults if none. */ function readConsent() {
@@ -21,24 +23,29 @@ function injectScript(src) {
document.head.appendChild(s);
}
/**
* Loads Google Analytics — GTM if a container ID is set, otherwise GA4 gtag.
* Loads every configured analytics / marketing tag, each respecting consent:
*
* Consent Mode is initialised to the visitor's stored consent BEFORE the tag
* loads (via setDefaultConsent from the consent module), so tags respect the
* choice from the first hit; useConsent sends an update the moment the visitor
* decides. IDs are public and come from SiteIntegrations, passed in as props
* (the client project reads them server-side).
* - **Google (GA4 / GTM)** — loaded immediately with Consent Mode: the visitor's
* stored choice is set as the default BEFORE the tag loads, and useConsent
* pushes an update the moment they decide. GTM wins if both IDs are set.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — these vendors have
* no Consent Mode, so they load ONLY after the matching category is granted
* (marketing for Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to
* the consent banner: accept → the tag loads immediately, no reload.
*
* Renders nothing — it only injects the scripts. Mount once, high in the tree
* (e.g. root layout), inside ConsentProvider.
*/ export function Analytics({ ga4MeasurementId, gtmContainerId }) {
* All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed
* in as props. Renders nothing. Mount once, high in the tree, INSIDE
* <ConsentProvider> (required — it reads live consent state).
*/ export function Analytics(props) {
const { clarityProjectId, ga4MeasurementId, gtmContainerId, linkedInPartnerId, metaPixelId, tiktokPixelId } = props;
// Live consent state — drives the non-Google pixels.
const { state } = useConsentContext();
// --- Google: load once, Consent Mode handles gating ---
useEffect(()=>{
if (!ga4MeasurementId && !gtmContainerId) {
return;
}
// 1. Consent Mode default = the visitor's stored choice, before tags load.
setDefaultConsent(readConsent());
// 2. Load the tag.
if (gtmContainerId) {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
@@ -48,8 +55,6 @@ function injectScript(src) {
injectScript(GTM_SCRIPT(gtmContainerId));
} else if (ga4MeasurementId) {
injectScript(GA4_SCRIPT(ga4MeasurementId));
// Uses the shared gtag (pushes `arguments`, as Google's tags expect);
// real gtag.js wires itself up once the script loads.
gtag('js', new Date());
gtag('config', ga4MeasurementId);
}
@@ -57,6 +62,32 @@ function injectScript(src) {
ga4MeasurementId,
gtmContainerId
]);
// --- Non-Google: load each when its consent category is granted ---
// The loaders are idempotent, so re-running on state changes is safe; a tag
// loads the first time its category flips to true and never doubles up.
useEffect(()=>{
if (state.marketing) {
if (metaPixelId) {
loadMetaPixel(metaPixelId);
}
if (linkedInPartnerId) {
loadLinkedIn(linkedInPartnerId);
}
if (tiktokPixelId) {
loadTikTok(tiktokPixelId);
}
}
if (state.analytics && clarityProjectId) {
loadClarity(clarityProjectId);
}
}, [
state.marketing,
state.analytics,
metaPixelId,
linkedInPartnerId,
tiktokPixelId,
clarityProjectId
]);
return null;
}
File diff suppressed because one or more lines are too long
+1
View File
@@ -1,2 +1,3 @@
export { Analytics } from './Analytics.js';
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js';
export { pushDataLayer } from './pushDataLayer.js';
+3
View File
@@ -1,5 +1,8 @@
'use client';
export { Analytics } from './Analytics.js';
// Low-level pixel loaders — exported for manual conversion events if a project
// needs them (Analytics loads them automatically, consent-gated).
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js';
export { pushDataLayer } from './pushDataLayer.js';
//# sourceMappingURL=client.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/analytics/client.ts"],"sourcesContent":["'use client'\nexport { Analytics } from './Analytics.js'\nexport { pushDataLayer } from './pushDataLayer.js'\n"],"names":["Analytics","pushDataLayer"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,aAAa,QAAQ,qBAAoB"}
{"version":3,"sources":["../../../src/modules/analytics/client.ts"],"sourcesContent":["'use client'\nexport { Analytics } from './Analytics.js'\n// Low-level pixel loaders — exported for manual conversion events if a project\n// needs them (Analytics loads them automatically, consent-gated).\nexport { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'\nexport { pushDataLayer } from './pushDataLayer.js'\n"],"names":["Analytics","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","pushDataLayer"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iBAAgB;AAC1C,+EAA+E;AAC/E,kEAAkE;AAClE,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,EAAEC,UAAU,QAAQ,cAAa;AAClF,SAASC,aAAa,QAAQ,qBAAoB"}
+2 -3
View File
@@ -1,9 +1,8 @@
import type { BasePayload } from 'payload';
import type { AnalyticsConfig } from './types.js';
/**
* Reads the public analytics IDs from SiteIntegrations, server-side.
*
* Returns only the two public IDs (GA4 / GTM) — safe to pass to the client
* Reads the public analytics / marketing tag IDs from SiteIntegrations,
* server-side. All are public (exposed client-side), so safe to pass to the
* <Analytics> component. Does NOT expose any secret from SiteIntegrations.
*/
export declare function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig>;
+7 -4
View File
@@ -1,14 +1,17 @@
import { getSiteIntegrations } from '../payload/index.js';
/**
* Reads the public analytics IDs from SiteIntegrations, server-side.
*
* Returns only the two public IDs (GA4 / GTM) — safe to pass to the client
* Reads the public analytics / marketing tag IDs from SiteIntegrations,
* server-side. All are public (exposed client-side), so safe to pass to the
* <Analytics> component. Does NOT expose any secret from SiteIntegrations.
*/ export async function getAnalyticsConfig(payload) {
const integrations = await getSiteIntegrations(payload);
return {
clarityProjectId: integrations.clarityProjectId ?? null,
ga4MeasurementId: integrations.ga4MeasurementId ?? null,
gtmContainerId: integrations.gtmContainerId ?? null
gtmContainerId: integrations.gtmContainerId ?? null,
linkedInPartnerId: integrations.linkedInPartnerId ?? null,
metaPixelId: integrations.metaPixelId ?? null,
tiktokPixelId: integrations.tiktokPixelId ?? null
};
}
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/analytics/getAnalyticsConfig.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { AnalyticsConfig } from './types.js'\n\nimport { getSiteIntegrations } from '../payload/index.js'\n\n/**\n * Reads the public analytics IDs from SiteIntegrations, server-side.\n *\n * Returns only the two public IDs (GA4 / GTM) — safe to pass to the client\n * <Analytics> component. Does NOT expose any secret from SiteIntegrations.\n */\nexport async function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig> {\n const integrations = await getSiteIntegrations<AnalyticsConfig>(payload)\n return {\n ga4MeasurementId: integrations.ga4MeasurementId ?? null,\n gtmContainerId: integrations.gtmContainerId ?? null,\n }\n}\n"],"names":["getSiteIntegrations","getAnalyticsConfig","payload","integrations","ga4MeasurementId","gtmContainerId"],"mappings":"AAIA,SAASA,mBAAmB,QAAQ,sBAAqB;AAEzD;;;;;CAKC,GACD,OAAO,eAAeC,mBAAmBC,OAAoB;IAC3D,MAAMC,eAAe,MAAMH,oBAAqCE;IAChE,OAAO;QACLE,kBAAkBD,aAAaC,gBAAgB,IAAI;QACnDC,gBAAgBF,aAAaE,cAAc,IAAI;IACjD;AACF"}
{"version":3,"sources":["../../../src/modules/analytics/getAnalyticsConfig.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { AnalyticsConfig } from './types.js'\n\nimport { getSiteIntegrations } from '../payload/index.js'\n\n/**\n * Reads the public analytics / marketing tag IDs from SiteIntegrations,\n * server-side. All are public (exposed client-side), so safe to pass to the\n * <Analytics> component. Does NOT expose any secret from SiteIntegrations.\n */\nexport async function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig> {\n const integrations = await getSiteIntegrations<AnalyticsConfig>(payload)\n return {\n clarityProjectId: integrations.clarityProjectId ?? null,\n ga4MeasurementId: integrations.ga4MeasurementId ?? null,\n gtmContainerId: integrations.gtmContainerId ?? null,\n linkedInPartnerId: integrations.linkedInPartnerId ?? null,\n metaPixelId: integrations.metaPixelId ?? null,\n tiktokPixelId: integrations.tiktokPixelId ?? null,\n }\n}\n"],"names":["getSiteIntegrations","getAnalyticsConfig","payload","integrations","clarityProjectId","ga4MeasurementId","gtmContainerId","linkedInPartnerId","metaPixelId","tiktokPixelId"],"mappings":"AAIA,SAASA,mBAAmB,QAAQ,sBAAqB;AAEzD;;;;CAIC,GACD,OAAO,eAAeC,mBAAmBC,OAAoB;IAC3D,MAAMC,eAAe,MAAMH,oBAAqCE;IAChE,OAAO;QACLE,kBAAkBD,aAAaC,gBAAgB,IAAI;QACnDC,kBAAkBF,aAAaE,gBAAgB,IAAI;QACnDC,gBAAgBH,aAAaG,cAAc,IAAI;QAC/CC,mBAAmBJ,aAAaI,iBAAiB,IAAI;QACrDC,aAAaL,aAAaK,WAAW,IAAI;QACzCC,eAAeN,aAAaM,aAAa,IAAI;IAC/C;AACF"}
+21
View File
@@ -0,0 +1,21 @@
/**
* Loaders for non-Google marketing/analytics pixels. Each is idempotent (guards
* against double-init) and loads the vendor's own script + bootstrap.
*
* These are the one place `any` is unavoidable: vendor SDK bootstraps attach
* untyped globals (fbq, clarity, lintrk, ttq) to `window`. Casts are contained
* here; nothing else in the kit uses `any`.
*
* CONSENT: these vendors have no Google Consent Mode — the caller (Analytics)
* loads each ONLY after the matching consent category is granted:
* Meta Pixel / LinkedIn / TikTok → marketing
* Microsoft Clarity → analytics
*/
/** Meta (Facebook) Pixel — fires PageView on load. */
export declare function loadMetaPixel(id: string): void;
/** Microsoft Clarity — heatmaps / session recordings (analytics category). */
export declare function loadClarity(id: string): void;
/** LinkedIn Insight Tag (marketing). */
export declare function loadLinkedIn(partnerId: string): void;
/** TikTok Pixel (marketing) — fires page view on load. */
export declare function loadTikTok(id: string): void;
+134
View File
@@ -0,0 +1,134 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /**
* Loaders for non-Google marketing/analytics pixels. Each is idempotent (guards
* against double-init) and loads the vendor's own script + bootstrap.
*
* These are the one place `any` is unavoidable: vendor SDK bootstraps attach
* untyped globals (fbq, clarity, lintrk, ttq) to `window`. Casts are contained
* here; nothing else in the kit uses `any`.
*
* CONSENT: these vendors have no Google Consent Mode — the caller (Analytics)
* loads each ONLY after the matching consent category is granted:
* Meta Pixel / LinkedIn / TikTok → marketing
* Microsoft Clarity → analytics
*/ /** Meta (Facebook) Pixel — fires PageView on load. */ export function loadMetaPixel(id) {
if (typeof window === 'undefined') {
return;
}
const w = window;
if (w.fbq) {
return;
}
const n = w.fbq = function(...args) {
if (n.callMethod) {
n.callMethod.apply(n, args);
} else {
n.queue.push(args);
}
};
if (!w._fbq) {
w._fbq = n;
}
n.push = n;
n.loaded = true;
n.version = '2.0';
n.queue = [];
const s = document.createElement('script');
s.async = true;
s.src = 'https://connect.facebook.net/en_US/fbevents.js';
document.head.appendChild(s);
w.fbq('init', id);
w.fbq('track', 'PageView');
}
/** Microsoft Clarity — heatmaps / session recordings (analytics category). */ export function loadClarity(id) {
if (typeof window === 'undefined') {
return;
}
const w = window;
if (w.clarity) {
return;
}
w.clarity = function(...a) {
;
(w.clarity.q = w.clarity.q || []).push(a);
};
const s = document.createElement('script');
s.async = true;
s.src = `https://www.clarity.ms/tag/${id}`;
document.head.appendChild(s);
}
/** LinkedIn Insight Tag (marketing). */ export function loadLinkedIn(partnerId) {
if (typeof window === 'undefined') {
return;
}
const w = window;
w._linkedin_partner_id = partnerId;
w._linkedin_data_partner_ids = w._linkedin_data_partner_ids || [];
if (w._linkedin_data_partner_ids.includes(partnerId)) {
if (document.getElementById('ipal-linkedin-insight')) {
return;
}
} else {
w._linkedin_data_partner_ids.push(partnerId);
}
if (document.getElementById('ipal-linkedin-insight')) {
return;
}
const s = document.createElement('script');
s.async = true;
s.id = 'ipal-linkedin-insight';
s.src = 'https://snap.licdn.com/li.lms-analytics/insight.min.js';
document.head.appendChild(s);
}
/** TikTok Pixel (marketing) — fires page view on load. */ export function loadTikTok(id) {
if (typeof window === 'undefined') {
return;
}
const w = window;
if (w.ttq) {
return;
}
w.TiktokAnalyticsObject = 'ttq';
const ttq = w.ttq = [];
ttq.methods = [
'page',
'track',
'identify',
'instances',
'debug',
'on',
'off',
'once',
'ready',
'alias',
'group',
'enableCookie',
'disableCookie'
];
ttq.setAndDefer = function(t, e) {
t[e] = function(...args) {
t.push([
e,
...args
]);
};
};
for (const m of ttq.methods){
ttq.setAndDefer(ttq, m);
}
ttq.load = function(e) {
const url = 'https://analytics.tiktok.com/i18n/pixel/events.js';
ttq._i = ttq._i || {};
ttq._i[e] = [];
ttq._i[e]._u = url;
ttq._t = ttq._t || {};
ttq._t[e] = Number(new Date());
const s = document.createElement('script');
s.async = true;
s.src = `${url}?sdkid=${e}&lib=ttq`;
document.head.appendChild(s);
};
ttq.load(id);
ttq.page();
}
//# sourceMappingURL=pixels.js.map
File diff suppressed because one or more lines are too long
+13 -3
View File
@@ -1,9 +1,19 @@
/**
* Analytics IDs, read from SiteIntegrations (public — safe on the client).
* Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe
* on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only
* after the matching consent category is granted (see Analytics).
*/
export type AnalyticsConfig = {
/** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. */
/** Microsoft Clarity project ID. (analytics consent) */
clarityProjectId?: null | string;
/** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. (Google — Consent Mode) */
ga4MeasurementId?: null | string;
/** GTM Container ID, e.g. 'GTM-XXXXXXX'. */
/** GTM Container ID, e.g. 'GTM-XXXXXXX'. (Google — Consent Mode) */
gtmContainerId?: null | string;
/** LinkedIn Insight Tag partner ID. (marketing consent) */
linkedInPartnerId?: null | string;
/** Meta (Facebook) Pixel ID, ~15–16 digits. (marketing consent) */
metaPixelId?: null | string;
/** TikTok Pixel ID. (marketing consent) */
tiktokPixelId?: null | string;
};
+3 -1
View File
@@ -1,5 +1,7 @@
/**
* Analytics IDs, read from SiteIntegrations (public — safe on the client).
* Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe
* on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only
* after the matching consent category is granted (see Analytics).
*/ export { };
//# sourceMappingURL=types.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/analytics/types.ts"],"sourcesContent":["/**\n * Analytics IDs, read from SiteIntegrations (public — safe on the client).\n */\nexport type AnalyticsConfig = {\n /** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. */\n ga4MeasurementId?: null | string\n /** GTM Container ID, e.g. 'GTM-XXXXXXX'. */\n gtmContainerId?: null | string\n}\n"],"names":[],"mappings":"AAAA;;CAEC,GACD,WAKC"}
{"version":3,"sources":["../../../src/modules/analytics/types.ts"],"sourcesContent":["/**\n * Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe\n * on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only\n * after the matching consent category is granted (see Analytics).\n */\nexport type AnalyticsConfig = {\n /** Microsoft Clarity project ID. (analytics consent) */\n clarityProjectId?: null | string\n /** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. (Google — Consent Mode) */\n ga4MeasurementId?: null | string\n /** GTM Container ID, e.g. 'GTM-XXXXXXX'. (Google — Consent Mode) */\n gtmContainerId?: null | string\n /** LinkedIn Insight Tag partner ID. (marketing consent) */\n linkedInPartnerId?: null | string\n /** Meta (Facebook) Pixel ID, ~15–16 digits. (marketing consent) */\n metaPixelId?: null | string\n /** TikTok Pixel ID. (marketing consent) */\n tiktokPixelId?: null | string\n}\n"],"names":[],"mappings":"AAAA;;;;CAIC,GACD,WAaC"}
+1
View File
@@ -6,6 +6,7 @@ export { getArchiveEntries } from './getArchiveEntries.js';
export type { ArchiveEntries } from './getArchiveEntries.js';
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js';
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
export { resolveNotFoundPage } from './resolveNotFoundPage.js';
export { resolveRedirect } from './resolveRedirect.js';
export { resolveRoute } from './resolveRoute.js';
export type { ResolvedRoute } from './resolveRoute.js';
+1
View File
@@ -5,6 +5,7 @@ export { createSearchRoute } from './createSearchRoute.js';
export { getArchiveEntries } from './getArchiveEntries.js';
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js';
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
export { resolveNotFoundPage } from './resolveNotFoundPage.js';
export { resolveRedirect } from './resolveRedirect.js';
export { resolveRoute } from './resolveRoute.js';
export { searchContent } from './searchContent.js';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { blocksToMarkdown } from './blocksToMarkdown.js'\nexport { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'\nexport { createSearchRoute } from './createSearchRoute.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveRedirect } from './resolveRedirect.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport { searchContent } from './searchContent.js'\nexport type { SearchResult } from './searchContent.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","blocksToMarkdown","createMarkdownRenderer","markdownResponse","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","prefersMarkdown","buildArchivePath","buildEntryPath","parsePageParam","resolveRedirect","resolveRoute","searchContent","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,8BAA6B;AACtF,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,eAAe,EAAEC,YAAY,EAAEC,eAAe,QAAQ,2BAA0B;AACzF,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,aAAa,QAAQ,qBAAoB;AAGlD,SAASC,gBAAgB,QAAQ,aAAY"}
{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { blocksToMarkdown } from './blocksToMarkdown.js'\nexport { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'\nexport { createSearchRoute } from './createSearchRoute.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveNotFoundPage } from './resolveNotFoundPage.js'\nexport { resolveRedirect } from './resolveRedirect.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport { searchContent } from './searchContent.js'\nexport type { SearchResult } from './searchContent.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","blocksToMarkdown","createMarkdownRenderer","markdownResponse","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","prefersMarkdown","buildArchivePath","buildEntryPath","parsePageParam","resolveNotFoundPage","resolveRedirect","resolveRoute","searchContent","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,8BAA6B;AACtF,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,eAAe,EAAEC,YAAY,EAAEC,eAAe,QAAQ,2BAA0B;AACzF,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,aAAa,QAAQ,qBAAoB;AAGlD,SAASC,gBAAgB,QAAQ,aAAY"}
+23
View File
@@ -0,0 +1,23 @@
import type { BasePayload } from 'payload';
type ResolveNotFoundPageArgs = {
locale: string;
/** Client's Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string;
payload: BasePayload;
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string;
};
/**
* Returns the page the editor assigned as **404 (Not Found)** in System Pages,
* fully populated (depth 2, same shape as resolveRoute's pages), or null when
* the role is unassigned.
*
* Used by the project's `not-found.tsx`. The editor decides what a 404 looks
* like: a dedicated "Not found" page, or simply the homepage. Null means
* "render the project's built-in fallback view".
*
* Never throws — a missing DB (container build prerendering not-found) or a
* deleted page just yields null, so the 404 view can't crash the build.
*/
export declare function resolveNotFoundPage({ locale, pagesSlug, payload, settingsSlug, }: ResolveNotFoundPageArgs): Promise<null | Record<string, unknown>>;
export {};
+37
View File
@@ -0,0 +1,37 @@
/**
* Returns the page the editor assigned as **404 (Not Found)** in System Pages,
* fully populated (depth 2, same shape as resolveRoute's pages), or null when
* the role is unassigned.
*
* Used by the project's `not-found.tsx`. The editor decides what a 404 looks
* like: a dedicated "Not found" page, or simply the homepage. Null means
* "render the project's built-in fallback view".
*
* Never throws — a missing DB (container build prerendering not-found) or a
* deleted page just yields null, so the 404 view can't crash the build.
*/ export async function resolveNotFoundPage({ locale, pagesSlug = 'pages', payload, settingsSlug = 'site-settings' }) {
try {
const settings = await payload.findGlobal({
slug: settingsSlug,
depth: 0,
locale: locale
});
const rel = settings.notFound;
const id = typeof rel === 'string' || typeof rel === 'number' ? rel : rel && typeof rel === 'object' ? rel.id : undefined;
if (id === undefined) {
return null;
}
const doc = await payload.findByID({
id,
collection: pagesSlug,
depth: 2,
locale: locale
});
return doc ?? null;
} catch (error) {
console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error);
return null;
}
}
//# sourceMappingURL=resolveNotFoundPage.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/content/resolveNotFoundPage.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\ntype ResolveNotFoundPageArgs = {\n locale: string\n /** Client's Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n payload: BasePayload\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n}\n\n/**\n * Returns the page the editor assigned as **404 (Not Found)** in System Pages,\n * fully populated (depth 2, same shape as resolveRoute's pages), or null when\n * the role is unassigned.\n *\n * Used by the project's `not-found.tsx`. The editor decides what a 404 looks\n * like: a dedicated \"Not found\" page, or simply the homepage. Null means\n * \"render the project's built-in fallback view\".\n *\n * Never throws — a missing DB (container build prerendering not-found) or a\n * deleted page just yields null, so the 404 view can't crash the build.\n */\nexport async function resolveNotFoundPage({\n locale,\n pagesSlug = 'pages',\n payload,\n settingsSlug = 'site-settings',\n}: ResolveNotFoundPageArgs): Promise<null | Record<string, unknown>> {\n try {\n const settings = (await payload.findGlobal({\n slug: settingsSlug as never,\n depth: 0,\n locale: locale as never,\n })) as Record<string, unknown>\n\n const rel = settings.notFound\n const id =\n typeof rel === 'string' || typeof rel === 'number'\n ? rel\n : rel && typeof rel === 'object'\n ? (rel as { id?: number | string }).id\n : undefined\n if (id === undefined) {return null}\n\n const doc = await payload.findByID({\n id,\n collection: pagesSlug as never,\n depth: 2,\n locale: locale as never,\n })\n return (doc as null | Record<string, unknown>) ?? null\n } catch (error) {\n console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error)\n return null\n }\n}\n"],"names":["resolveNotFoundPage","locale","pagesSlug","payload","settingsSlug","settings","findGlobal","slug","depth","rel","notFound","id","undefined","doc","findByID","collection","error","console","warn"],"mappings":"AAWA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeA,oBAAoB,EACxCC,MAAM,EACNC,YAAY,OAAO,EACnBC,OAAO,EACPC,eAAe,eAAe,EACN;IACxB,IAAI;QACF,MAAMC,WAAY,MAAMF,QAAQG,UAAU,CAAC;YACzCC,MAAMH;YACNI,OAAO;YACPP,QAAQA;QACV;QAEA,MAAMQ,MAAMJ,SAASK,QAAQ;QAC7B,MAAMC,KACJ,OAAOF,QAAQ,YAAY,OAAOA,QAAQ,WACtCA,MACAA,OAAO,OAAOA,QAAQ,WACpB,AAACA,IAAiCE,EAAE,GACpCC;QACR,IAAID,OAAOC,WAAW;YAAC,OAAO;QAAI;QAElC,MAAMC,MAAM,MAAMV,QAAQW,QAAQ,CAAC;YACjCH;YACAI,YAAYb;YACZM,OAAO;YACPP,QAAQA;QACV;QACA,OAAO,AAACY,OAA0C;IACpD,EAAE,OAAOG,OAAO;QACdC,QAAQC,IAAI,CAAC,kEAAkEF;QAC/E,OAAO;IACT;AACF"}
+14
View File
@@ -114,6 +114,20 @@ import { archiveFieldName } from './types.js';
if (!doc) {
return null;
}
// The page assigned as 404 in System Pages must not be reachable as a normal
// 200 URL (/pl/strona-nie-znaleziona) — that's a soft-404 / duplicate. Treat
// it as not found, so the route calls notFound() and not-found.tsx renders
// that same page with a real 404 status. (If 404 = homepage, the homepage is
// served from the root branch above and never reaches here by its own slug
// in a way that matters — but guard anyway so we never hide the homepage.)
const notFound = settings.notFound;
const homepage = settings.homepage;
const notFoundId = notFound && typeof notFound === 'object' ? notFound.id : notFound;
const homepageId = homepage && typeof homepage === 'object' ? homepage.id : homepage;
const docId = doc.id;
if (notFoundId != null && notFoundId === docId && notFoundId !== homepageId) {
return null;
}
return {
type: 'page',
doc: doc
File diff suppressed because one or more lines are too long
+1
View File
@@ -62,6 +62,7 @@ export declare function createContentHelpers({ baseUrl, config, content, i18n, p
getCachedPayload: () => Promise<BasePayload>;
getConfiguredLocales: () => Promise<string[]>;
getEntries: (collection: string, locale: string, page: number, perPage: number) => Promise<ArchiveEntries>;
getNotFoundPage: (locale: string) => Promise<Record<string, unknown> | null>;
getSettings: (locale: string) => Promise<import("payload").JsonObject>;
resolveRoute: (locale: string, segments: string[] | undefined, page: number) => Promise<null | ResolvedRoute>;
robots: () => RobotsRules;
+25 -1
View File
@@ -1,6 +1,6 @@
import { getPayload } from 'payload';
import { cache } from 'react';
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js';
import { getArchiveEntries, resolveNotFoundPage, resolveRoute as resolveRouteRaw } from '../content/index.js';
import { buildRobots, buildSitemapEntries } from '../seo/index.js';
/**
* Bundles the per-request data helpers a frontend needs — the same cached
@@ -56,6 +56,24 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
settingsSlug
});
});
/**
* The page assigned as 404 in System Pages (or null → built-in fallback).
* For app/not-found.tsx; never throws. Locale comes from the x-locale header
* set by createProxy (not-found.tsx receives no params).
*/ const getNotFoundPage = cache(async (locale)=>{
try {
const payload = await getCachedPayload();
return await resolveNotFoundPage({
locale,
pagesSlug,
payload,
settingsSlug
});
} catch {
return null // DB unreachable (container build) — fallback view
;
}
});
/** One page of a collection's entries, for an archive listing. */ const getEntries = cache(async (collection, locale, page, perPage)=>{
const payload = await getCachedPayload();
return getArchiveEntries({
@@ -154,6 +172,8 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
locale: 'all'
}).catch(()=>null);
const homeId = settings?.homepage?.id;
// The assigned 404 page renders via not-found.tsx, never as its own URL.
const notFoundId = settings?.notFound?.id !== undefined && settings.notFound.id !== homeId ? settings.notFound.id : undefined;
const EXCLUDED = new Set([
'404',
'500',
@@ -177,6 +197,9 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
if (raw._status && raw._status !== 'published') {
continue;
}
if (notFoundId !== undefined && raw.id === notFoundId) {
continue;
}
// NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex
// page (privacy, cookies, terms) still needs to render — users reach it
// from the footer and crawlers read its <meta robots=noindex>. Pre-render
@@ -230,6 +253,7 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
getCachedPayload,
getConfiguredLocales,
getEntries,
getNotFoundPage,
getSettings,
resolveRoute,
robots,
File diff suppressed because one or more lines are too long
+2
View File
@@ -2,12 +2,14 @@ import { ALL_SYSTEM_PAGE_ROLES } from './types.js';
/** Admin-facing labels per role. */ const ROLE_LABELS = {
cookiePolicy: 'Cookie Policy',
homepage: 'Homepage',
notFound: '404 (Not Found)',
privacyPolicy: 'Privacy Policy',
termsOfService: 'Terms of Service'
};
/** Admin descriptions per role. */ const ROLE_DESCRIPTIONS = {
cookiePolicy: 'Page linked from the cookie consent banner.',
homepage: 'Page served at the locale root (e.g. /pl, /en).',
notFound: 'Page shown for unknown URLs (404). Pick a dedicated "Not found" page, or reuse the homepage. If left empty, the project falls back to its built-in not-found view.',
privacyPolicy: 'Page linked as the privacy policy.',
termsOfService: 'Page linked as the terms of service / site regulations.'
};
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/pages/systemPagesFields.ts"],"sourcesContent":["import type { Field, RelationshipField } from 'payload'\n\nimport type { PagesOption, SystemPageRole } from './types.js'\n\nimport { ALL_SYSTEM_PAGE_ROLES } from './types.js'\n\n/** Admin-facing labels per role. */\nconst ROLE_LABELS: Record<SystemPageRole, string> = {\n cookiePolicy: 'Cookie Policy',\n homepage: 'Homepage',\n privacyPolicy: 'Privacy Policy',\n termsOfService: 'Terms of Service',\n}\n\n/** Admin descriptions per role. */\nconst ROLE_DESCRIPTIONS: Record<SystemPageRole, string> = {\n cookiePolicy: 'Page linked from the cookie consent banner.',\n homepage: 'Page served at the locale root (e.g. /pl, /en).',\n privacyPolicy: 'Page linked as the privacy policy.',\n termsOfService: 'Page linked as the terms of service / site regulations.',\n}\n\n/**\n * Builds one relationship field per configured system-page role.\n *\n * Each field points at the client's Pages collection (via the provided slug)\n * and holds a single document reference. The referenced document's slug is\n * localized, so the same assignment resolves to /pl/strona-glowna and\n * /en/home at runtime — role assignment is locale-agnostic, path resolution\n * is locale-aware (see getSystemPagePath).\n */\nexport function buildSystemPagesFields(pages: PagesOption): Field[] {\n const roles = pages.roles?.length ? pages.roles : [...ALL_SYSTEM_PAGE_ROLES]\n\n return roles.map((role): RelationshipField => ({\n name: role,\n type: 'relationship',\n admin: {\n description: ROLE_DESCRIPTIONS[role],\n },\n label: ROLE_LABELS[role],\n maxDepth: 1,\n relationTo: pages.slug,\n }))\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES","ROLE_LABELS","cookiePolicy","homepage","privacyPolicy","termsOfService","ROLE_DESCRIPTIONS","buildSystemPagesFields","pages","roles","length","map","role","name","type","admin","description","label","maxDepth","relationTo","slug"],"mappings":"AAIA,SAASA,qBAAqB,QAAQ,aAAY;AAElD,kCAAkC,GAClC,MAAMC,cAA8C;IAClDC,cAAc;IACdC,UAAU;IACVC,eAAe;IACfC,gBAAgB;AAClB;AAEA,iCAAiC,GACjC,MAAMC,oBAAoD;IACxDJ,cAAc;IACdC,UAAU;IACVC,eAAe;IACfC,gBAAgB;AAClB;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASE,uBAAuBC,KAAkB;IACvD,MAAMC,QAAQD,MAAMC,KAAK,EAAEC,SAASF,MAAMC,KAAK,GAAG;WAAIT;KAAsB;IAE5E,OAAOS,MAAME,GAAG,CAAC,CAACC,OAA6B,CAAA;YAC7CC,MAAMD;YACNE,MAAM;YACNC,OAAO;gBACLC,aAAaV,iBAAiB,CAACM,KAAK;YACtC;YACAK,OAAOhB,WAAW,CAACW,KAAK;YACxBM,UAAU;YACVC,YAAYX,MAAMY,IAAI;QACxB,CAAA;AACF"}
{"version":3,"sources":["../../../src/modules/pages/systemPagesFields.ts"],"sourcesContent":["import type { Field, RelationshipField } from 'payload'\n\nimport type { PagesOption, SystemPageRole } from './types.js'\n\nimport { ALL_SYSTEM_PAGE_ROLES } from './types.js'\n\n/** Admin-facing labels per role. */\nconst ROLE_LABELS: Record<SystemPageRole, string> = {\n cookiePolicy: 'Cookie Policy',\n homepage: 'Homepage',\n notFound: '404 (Not Found)',\n privacyPolicy: 'Privacy Policy',\n termsOfService: 'Terms of Service',\n}\n\n/** Admin descriptions per role. */\nconst ROLE_DESCRIPTIONS: Record<SystemPageRole, string> = {\n cookiePolicy: 'Page linked from the cookie consent banner.',\n homepage: 'Page served at the locale root (e.g. /pl, /en).',\n notFound:\n 'Page shown for unknown URLs (404). Pick a dedicated \"Not found\" page, or reuse the homepage. If left empty, the project falls back to its built-in not-found view.',\n privacyPolicy: 'Page linked as the privacy policy.',\n termsOfService: 'Page linked as the terms of service / site regulations.',\n}\n\n/**\n * Builds one relationship field per configured system-page role.\n *\n * Each field points at the client's Pages collection (via the provided slug)\n * and holds a single document reference. The referenced document's slug is\n * localized, so the same assignment resolves to /pl/strona-glowna and\n * /en/home at runtime — role assignment is locale-agnostic, path resolution\n * is locale-aware (see getSystemPagePath).\n */\nexport function buildSystemPagesFields(pages: PagesOption): Field[] {\n const roles = pages.roles?.length ? pages.roles : [...ALL_SYSTEM_PAGE_ROLES]\n\n return roles.map((role): RelationshipField => ({\n name: role,\n type: 'relationship',\n admin: {\n description: ROLE_DESCRIPTIONS[role],\n },\n label: ROLE_LABELS[role],\n maxDepth: 1,\n relationTo: pages.slug,\n }))\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES","ROLE_LABELS","cookiePolicy","homepage","notFound","privacyPolicy","termsOfService","ROLE_DESCRIPTIONS","buildSystemPagesFields","pages","roles","length","map","role","name","type","admin","description","label","maxDepth","relationTo","slug"],"mappings":"AAIA,SAASA,qBAAqB,QAAQ,aAAY;AAElD,kCAAkC,GAClC,MAAMC,cAA8C;IAClDC,cAAc;IACdC,UAAU;IACVC,UAAU;IACVC,eAAe;IACfC,gBAAgB;AAClB;AAEA,iCAAiC,GACjC,MAAMC,oBAAoD;IACxDL,cAAc;IACdC,UAAU;IACVC,UACE;IACFC,eAAe;IACfC,gBAAgB;AAClB;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASE,uBAAuBC,KAAkB;IACvD,MAAMC,QAAQD,MAAMC,KAAK,EAAEC,SAASF,MAAMC,KAAK,GAAG;WAAIV;KAAsB;IAE5E,OAAOU,MAAME,GAAG,CAAC,CAACC,OAA6B,CAAA;YAC7CC,MAAMD;YACNE,MAAM;YACNC,OAAO;gBACLC,aAAaV,iBAAiB,CAACM,KAAK;YACtC;YACAK,OAAOjB,WAAW,CAACY,KAAK;YACxBM,UAAU;YACVC,YAAYX,MAAMY,IAAI;QACxB,CAAA;AACF"}
+1 -1
View File
@@ -2,7 +2,7 @@
* Built-in "system page" roles — documents from the client's Pages
* collection that the site references by function rather than by slug.
*/
export type SystemPageRole = 'cookiePolicy' | 'homepage' | 'privacyPolicy' | 'termsOfService';
export type SystemPageRole = 'cookiePolicy' | 'homepage' | 'notFound' | 'privacyPolicy' | 'termsOfService';
/**
* All system roles in a stable order (used when no subset is configured).
*/
+1
View File
@@ -5,6 +5,7 @@
* All system roles in a stable order (used when no subset is configured).
*/ export const ALL_SYSTEM_PAGE_ROLES = [
'homepage',
'notFound',
'privacyPolicy',
'cookiePolicy',
'termsOfService'
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/pages/types.ts"],"sourcesContent":["/**\n * Built-in \"system page\" roles — documents from the client's Pages\n * collection that the site references by function rather than by slug.\n */\nexport type SystemPageRole = 'cookiePolicy' | 'homepage' | 'privacyPolicy' | 'termsOfService'\n\n/**\n * All system roles in a stable order (used when no subset is configured).\n */\nexport const ALL_SYSTEM_PAGE_ROLES: readonly SystemPageRole[] = [\n 'homepage',\n 'privacyPolicy',\n 'cookiePolicy',\n 'termsOfService',\n]\n\n/**\n * Plugin option enabling system-page assignments in SiteSettings.\n *\n * The plugin doesn't own the Pages collection — the client creates it in\n * their own project. This option hands the plugin the collection's slug so\n * it can build relationship fields pointing at it. No hardcoding: the slug\n * always comes from the client.\n */\nexport type PagesOption = {\n /**\n * Which system roles to expose as assignable fields.\n * Defaults to all roles when omitted.\n */\n roles?: SystemPageRole[]\n /** Slug of the client's Pages collection, e.g. 'pages'. */\n slug: string\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES"],"mappings":"AAAA;;;CAGC,GAGD;;CAEC,GACD,OAAO,MAAMA,wBAAmD;IAC9D;IACA;IACA;IACA;CACD,CAAA"}
{"version":3,"sources":["../../../src/modules/pages/types.ts"],"sourcesContent":["/**\n * Built-in \"system page\" roles — documents from the client's Pages\n * collection that the site references by function rather than by slug.\n */\nexport type SystemPageRole =\n 'cookiePolicy' | 'homepage' | 'notFound' | 'privacyPolicy' | 'termsOfService'\n\n/**\n * All system roles in a stable order (used when no subset is configured).\n */\nexport const ALL_SYSTEM_PAGE_ROLES: readonly SystemPageRole[] = [\n 'homepage',\n 'notFound',\n 'privacyPolicy',\n 'cookiePolicy',\n 'termsOfService',\n]\n\n/**\n * Plugin option enabling system-page assignments in SiteSettings.\n *\n * The plugin doesn't own the Pages collection — the client creates it in\n * their own project. This option hands the plugin the collection's slug so\n * it can build relationship fields pointing at it. No hardcoding: the slug\n * always comes from the client.\n */\nexport type PagesOption = {\n /**\n * Which system roles to expose as assignable fields.\n * Defaults to all roles when omitted.\n */\n roles?: SystemPageRole[]\n /** Slug of the client's Pages collection, e.g. 'pages'. */\n slug: string\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES"],"mappings":"AAAA;;;CAGC,GAID;;CAEC,GACD,OAAO,MAAMA,wBAAmD;IAC9D;IACA;IACA;IACA;IACA;CACD,CAAA"}
+52 -10
View File
@@ -1,22 +1,58 @@
# analytics
Ładuje GA4 albo Google Tag Manager, spięte z modułem consent: Consent Mode
dostaje decyzję odwiedzającego, zanim tag się załaduje, i aktualizację w
momencie kliknięcia w banerze.
Ładuje tagi analityczne i marketingowe wpisane w panelu, każdy zgodnie ze
zgodą z modułu consent:
- **Google (GA4 / GTM)** — przez Consent Mode v2: tag ładuje się od razu, ale
dostaje decyzję odwiedzającego, zanim cokolwiek zmierzy.
- **Pozostałe (Meta Pixel, Microsoft Clarity, LinkedIn Insight, TikTok Pixel)** —
nie mają Consent Mode, więc ładują się **dopiero po zgodzie** na właściwą
kategorię. Reagują na żywo: klik „Akceptuj” → tag startuje bez przeładowania.
## Config
Brak opcji w `payload.config` — plugin czyta ID z globala **Site Integrations**
(Settings → Site Integrations):
- **GA4 Measurement ID** — `G-XXXXXXXXXX`
- **GTM Container ID** — `GTM-XXXXXXX`
| Pole | Format | Kategoria zgody |
|---|---|---|
| GA4 Measurement ID | `G-XXXXXXXXXX` | Consent Mode (analytics_storage) |
| GTM Container ID | `GTM-XXXXXXX` | Consent Mode (wszystkie sygnały) |
| Meta Pixel ID | `1234567890123456` | **marketing** |
| Microsoft Clarity Project ID | `abcdefghij` | **analytics** |
| LinkedIn Partner ID | `1234567` | **marketing** |
| TikTok Pixel ID | `CXXXXXXXXXXXXXXXXXXX` | **marketing** |
Gdy ustawione są oba, wygrywa GTM. Gdy żadne — komponent nie robi nic.
GA4 + GTM ustawione jednocześnie → wygrywa GTM. Puste pole = tag się nie ładuje.
To jedyne pola z Site Integrations, które trafiają na klienta — są publiczne
(widać je w źródle każdej strony z GA). `getAnalyticsConfig` czyta wyłącznie je,
więc sekrety (Turnstile, SMTP) nie mają jak wyciec.
Wszystkie te ID są publiczne (widać je w źródle strony). `getAnalyticsConfig`
czyta wyłącznie je, więc sekrety (Turnstile, SMTP) nie mają jak wyciec.
### Pixel w panelu czy w GTM?
**Jedno albo drugie, nigdy oba** — inaczej każde zdarzenie liczy się
podwójnie. Zasada:
- Klient bez GTM / prosta strona → wpisz Pixel ID w panelu (najprościej,
zgoda obsłużona automatycznie).
- Klient ma agencję/marketera, który zarządza tagami w GTM → zostaw pole Pixel
puste, Pixel konfiguruje się w GTM z warunkiem `ad_storage` (patrz
[gtm-meta-pixel.md](./gtm-meta-pixel.md)).
### Zdarzenia konwersji (non-Google)
`Analytics` wysyła tylko `PageView`. Konwersje (np. Lead po formularzu) wołasz
sam — globale istnieją dopiero po zgodzie, więc zawsze ze strażnikiem:
```ts
window.fbq?.('track', 'Lead') // Meta
window.ttq?.track('SubmitForm') // TikTok
window.lintrk?.('track', { conversion_id: 123 }) // LinkedIn
```
Niskopoziomowe loadery (`loadMetaPixel`, `loadClarity`, `loadLinkedIn`,
`loadTikTok`) są eksportowane z `/client`, ale normalnie nie są potrzebne —
NIE wołaj ich z pominięciem zgody.
## Front
@@ -41,7 +77,8 @@ export default async function LocaleLayout({ children, params }) {
```
`Analytics` nie renderuje nic — wstrzykuje skrypty. Zamontuj raz, wysoko w
drzewie.
drzewie. **Musi być wewnątrz `ConsentProvider`** (od 1.8.0 czyta stan zgody na
żywo — poza providerem rzuci błąd kontekstu).
## Jak działa Consent Mode
@@ -68,6 +105,11 @@ W konsoli: `window.dataLayer` — powinien zawierać `Arguments(3)` z `consent`
Ciasteczko `_ga` pojawia się dopiero po zgodzie na analytics — to jest sedno
Consent Mode.
Pixele non-Google: przed zgodą w Network **nie może** być żądań do
`connect.facebook.net`, `clarity.ms`, `snap.licdn.com`, `analytics.tiktok.com`.
Po kliknięciu zgody pojawiają się od razu. Meta Pixel Helper (rozszerzenie
Chrome) powinien pokazać `PageView` dopiero po akceptacji marketingu.
## Zdarzenia do GTM — pushDataLayer
Do wypchnięcia własnego zdarzenia (np. `form_submit` pod tag Lead w GTM) jest
+49 -3
View File
@@ -1,7 +1,7 @@
# pages
System pages: centralne przypisanie ról (homepage / privacyPolicy /
cookiePolicy) do dokumentów z klienckiej kolekcji Pages, w SiteSettings.
System pages: centralne przypisanie ról (homepage / notFound / privacyPolicy /
cookiePolicy / termsOfService) do dokumentów z klienckiej kolekcji Pages, w SiteSettings.
Front rozwiązuje rolę na ścieżkę locale-aware.
## Config (payload.config.ts)
@@ -51,9 +51,55 @@ stopce / bannerze cookies bierzesz z `getSystemPagePath({ role: privacyPolicy })
```ts
import { ALL_SYSTEM_PAGE_ROLES } from '@intecion/ipal-kit'
// ['homepage', 'privacyPolicy', 'cookiePolicy']
// ['homepage', 'notFound', 'privacyPolicy', 'cookiePolicy', 'termsOfService']
```
## Strona 404 — wybierana w panelu (od 1.8.0)
Site Settings → System Pages → **404 (Not Found)**. Edytor wybiera:
- dedykowaną stronę „Nie znaleziono” (np. slug `strona-nie-znaleziona`), **albo**
- stronę główną (część klientów tak woli), **albo**
- nic → projekt pokazuje wbudowany fallback z `not-found.tsx`.
Projekt (`app/(frontend)/[locale]/not-found.tsx`) — gotowy przykład w
`frontend/[locale]/not-found.tsx`:
```tsx
import { headers } from 'next/headers'
import { getNotFoundPage } from '@/lib/content' // z createContentHelpers
export default async function NotFound() {
const locale = (await headers()).get('x-locale') ?? i18nConfig.defaultLocale
const page = await getNotFoundPage(locale) // null → fallback
if (page?.layout?.length) return <RenderBlocks blocks={page.layout} components={blockRegistry} />
return <Fallback404 locale={locale} />
}
```
`not-found.tsx` nie dostaje `params` — locale bierzemy z nagłówka `x-locale`,
który ustawia proxy z `createProxy`. Status HTTP zostaje **404** (renderuje go
Next po `notFound()`), treść jest z panelu.
Co plugin robi automatycznie z przypisaną stroną 404:
| Miejsce | Zachowanie |
|---|---|
| `resolveRoute` | bezpośrednie wejście na `/pl/strona-nie-znaleziona` → `null` → `notFound()` → prawdziwy 404 (bez soft-404 / duplikatu z kodem 200) |
| sitemap | wykluczona po ID (slug może być dowolny) |
| `generateStaticParams` | pominięta (nie jest osobnym URL-em) |
| `getNotFoundPage` / `resolveNotFoundPage` | nigdy nie rzuca — brak bazy w buildzie = fallback |
Gdy 404 = strona główna, nic z powyższego nie ukrywa strony głównej — dalej
działa pod `/{locale}` i jest w sitemapie; dodatkowo jej treść pokazuje się pod
nieznanymi URL-ami (z kodem 404).
Bez `createContentHelpers`: `resolveNotFoundPage({ payload, locale })` z
`@intecion/ipal-kit`.
Wskazówka: zaznacz na dedykowanej stronie 404 **noindex** — wtedy wypada też z
llms.txt i wyszukiwarki.
## KRYTYCZNE: generateStaticParams dla [[...slug]] (SEO + head)
Trasa `[[...slug]]` (opcjonalny catch-all) BEZ `generateStaticParams` jest przez
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.7.7",
"version": "1.7.8",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
@@ -1,15 +1,16 @@
import type { Field } from 'payload'
/**
* Analytics configuration — GA4 measurement ID and GTM container ID.
* IDs are public (exposed client-side), so no read restriction needed.
* Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no
* read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only
* after the matching consent category is granted (see modules/analytics).
*/
export const analyticsFields: Field[] = [
{
name: 'ga4MeasurementId',
type: 'text',
admin: {
description: 'Google Analytics 4 Measurement ID.',
description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)',
placeholder: 'G-XXXXXXXXXX',
},
},
@@ -17,8 +18,40 @@ export const analyticsFields: Field[] = [
name: 'gtmContainerId',
type: 'text',
admin: {
description: 'Google Tag Manager container ID.',
description: 'Google Tag Manager container ID. (Google — Consent Mode)',
placeholder: 'GTM-XXXXXXX',
},
},
{
name: 'metaPixelId',
type: 'text',
admin: {
description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.',
placeholder: '1234567890123456',
},
},
{
name: 'clarityProjectId',
type: 'text',
admin: {
description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.',
placeholder: 'abcdefghij',
},
},
{
name: 'linkedInPartnerId',
type: 'text',
admin: {
description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.',
placeholder: '1234567',
},
},
{
name: 'tiktokPixelId',
type: 'text',
admin: {
description: 'TikTok Pixel ID. Loads only after MARKETING consent.',
placeholder: 'CXXXXXXXXXXXXXXXXXXX',
},
},
]
+1
View File
@@ -56,6 +56,7 @@ export {
markdownResponse,
parsePageParam,
prefersMarkdown,
resolveNotFoundPage,
resolveRedirect,
resolveRoute,
searchContent,
+46 -15
View File
@@ -3,8 +3,10 @@ import { useEffect } from 'react'
import type { AnalyticsConfig } from './types.js'
import { useConsentContext } from '../consent/client.js'
import { gtag } from '../consent/googleConsent.js'
import { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js'
import { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'
declare global {
interface Window {
@@ -34,37 +36,66 @@ function injectScript(src: string) {
}
/**
* Loads Google Analytics — GTM if a container ID is set, otherwise GA4 gtag.
* Loads every configured analytics / marketing tag, each respecting consent:
*
* Consent Mode is initialised to the visitor's stored consent BEFORE the tag
* loads (via setDefaultConsent from the consent module), so tags respect the
* choice from the first hit; useConsent sends an update the moment the visitor
* decides. IDs are public and come from SiteIntegrations, passed in as props
* (the client project reads them server-side).
* - **Google (GA4 / GTM)** — loaded immediately with Consent Mode: the visitor's
* stored choice is set as the default BEFORE the tag loads, and useConsent
* pushes an update the moment they decide. GTM wins if both IDs are set.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — these vendors have
* no Consent Mode, so they load ONLY after the matching category is granted
* (marketing for Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to
* the consent banner: accept → the tag loads immediately, no reload.
*
* Renders nothing — it only injects the scripts. Mount once, high in the tree
* (e.g. root layout), inside ConsentProvider.
* All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed
* in as props. Renders nothing. Mount once, high in the tree, INSIDE
* <ConsentProvider> (required — it reads live consent state).
*/
export function Analytics({ ga4MeasurementId, gtmContainerId }: AnalyticsConfig) {
export function Analytics(props: AnalyticsConfig) {
const {
clarityProjectId,
ga4MeasurementId,
gtmContainerId,
linkedInPartnerId,
metaPixelId,
tiktokPixelId,
} = props
// Live consent state — drives the non-Google pixels.
const { state } = useConsentContext()
// --- Google: load once, Consent Mode handles gating ---
useEffect(() => {
if (!ga4MeasurementId && !gtmContainerId) {return}
// 1. Consent Mode default = the visitor's stored choice, before tags load.
setDefaultConsent(readConsent())
// 2. Load the tag.
if (gtmContainerId) {
window.dataLayer = window.dataLayer || []
window.dataLayer.push({ event: 'gtm.js', 'gtm.start': Date.now() })
injectScript(GTM_SCRIPT(gtmContainerId))
} else if (ga4MeasurementId) {
injectScript(GA4_SCRIPT(ga4MeasurementId))
// Uses the shared gtag (pushes `arguments`, as Google's tags expect);
// real gtag.js wires itself up once the script loads.
gtag('js', new Date())
gtag('config', ga4MeasurementId)
}
}, [ga4MeasurementId, gtmContainerId])
// --- Non-Google: load each when its consent category is granted ---
// The loaders are idempotent, so re-running on state changes is safe; a tag
// loads the first time its category flips to true and never doubles up.
useEffect(() => {
if (state.marketing) {
if (metaPixelId) {loadMetaPixel(metaPixelId)}
if (linkedInPartnerId) {loadLinkedIn(linkedInPartnerId)}
if (tiktokPixelId) {loadTikTok(tiktokPixelId)}
}
if (state.analytics && clarityProjectId) {loadClarity(clarityProjectId)}
}, [
state.marketing,
state.analytics,
metaPixelId,
linkedInPartnerId,
tiktokPixelId,
clarityProjectId,
])
return null
}
+3
View File
@@ -1,3 +1,6 @@
'use client'
export { Analytics } from './Analytics.js'
// Low-level pixel loaders — exported for manual conversion events if a project
// needs them (Analytics loads them automatically, consent-gated).
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'
export { pushDataLayer } from './pushDataLayer.js'
+6 -3
View File
@@ -5,15 +5,18 @@ import type { AnalyticsConfig } from './types.js'
import { getSiteIntegrations } from '../payload/index.js'
/**
* Reads the public analytics IDs from SiteIntegrations, server-side.
*
* Returns only the two public IDs (GA4 / GTM) — safe to pass to the client
* Reads the public analytics / marketing tag IDs from SiteIntegrations,
* server-side. All are public (exposed client-side), so safe to pass to the
* <Analytics> component. Does NOT expose any secret from SiteIntegrations.
*/
export async function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig> {
const integrations = await getSiteIntegrations<AnalyticsConfig>(payload)
return {
clarityProjectId: integrations.clarityProjectId ?? null,
ga4MeasurementId: integrations.ga4MeasurementId ?? null,
gtmContainerId: integrations.gtmContainerId ?? null,
linkedInPartnerId: integrations.linkedInPartnerId ?? null,
metaPixelId: integrations.metaPixelId ?? null,
tiktokPixelId: integrations.tiktokPixelId ?? null,
}
}
+118
View File
@@ -0,0 +1,118 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Loaders for non-Google marketing/analytics pixels. Each is idempotent (guards
* against double-init) and loads the vendor's own script + bootstrap.
*
* These are the one place `any` is unavoidable: vendor SDK bootstraps attach
* untyped globals (fbq, clarity, lintrk, ttq) to `window`. Casts are contained
* here; nothing else in the kit uses `any`.
*
* CONSENT: these vendors have no Google Consent Mode — the caller (Analytics)
* loads each ONLY after the matching consent category is granted:
* Meta Pixel / LinkedIn / TikTok → marketing
* Microsoft Clarity → analytics
*/
type Win = Record<string, any> & typeof window
/** Meta (Facebook) Pixel — fires PageView on load. */
export function loadMetaPixel(id: string): void {
if (typeof window === 'undefined') {return}
const w = window as Win
if (w.fbq) {return}
const n: any = (w.fbq = function (...args: unknown[]) {
if (n.callMethod) {
n.callMethod.apply(n, args)
} else {
n.queue.push(args)
}
})
if (!w._fbq) {w._fbq = n}
n.push = n
n.loaded = true
n.version = '2.0'
n.queue = []
const s = document.createElement('script')
s.async = true
s.src = 'https://connect.facebook.net/en_US/fbevents.js'
document.head.appendChild(s)
w.fbq('init', id)
w.fbq('track', 'PageView')
}
/** Microsoft Clarity — heatmaps / session recordings (analytics category). */
export function loadClarity(id: string): void {
if (typeof window === 'undefined') {return}
const w = window as Win
if (w.clarity) {return}
w.clarity = function (...a: unknown[]) {
;(w.clarity.q = w.clarity.q || []).push(a)
}
const s = document.createElement('script')
s.async = true
s.src = `https://www.clarity.ms/tag/${id}`
document.head.appendChild(s)
}
/** LinkedIn Insight Tag (marketing). */
export function loadLinkedIn(partnerId: string): void {
if (typeof window === 'undefined') {return}
const w = window as Win
w._linkedin_partner_id = partnerId
w._linkedin_data_partner_ids = w._linkedin_data_partner_ids || []
if (w._linkedin_data_partner_ids.includes(partnerId)) {
if (document.getElementById('ipal-linkedin-insight')) {return}
} else {
w._linkedin_data_partner_ids.push(partnerId)
}
if (document.getElementById('ipal-linkedin-insight')) {return}
const s = document.createElement('script')
s.async = true
s.id = 'ipal-linkedin-insight'
s.src = 'https://snap.licdn.com/li.lms-analytics/insight.min.js'
document.head.appendChild(s)
}
/** TikTok Pixel (marketing) — fires page view on load. */
export function loadTikTok(id: string): void {
if (typeof window === 'undefined') {return}
const w = window as Win
if (w.ttq) {return}
w.TiktokAnalyticsObject = 'ttq'
const ttq: any = (w.ttq = [])
ttq.methods = [
'page',
'track',
'identify',
'instances',
'debug',
'on',
'off',
'once',
'ready',
'alias',
'group',
'enableCookie',
'disableCookie',
]
ttq.setAndDefer = function (t: any, e: string) {
t[e] = function (...args: unknown[]) {
t.push([e, ...args])
}
}
for (const m of ttq.methods) {ttq.setAndDefer(ttq, m)}
ttq.load = function (e: string) {
const url = 'https://analytics.tiktok.com/i18n/pixel/events.js'
ttq._i = ttq._i || {}
ttq._i[e] = []
ttq._i[e]._u = url
ttq._t = ttq._t || {}
ttq._t[e] = Number(new Date())
const s = document.createElement('script')
s.async = true
s.src = `${url}?sdkid=${e}&lib=ttq`
document.head.appendChild(s)
}
ttq.load(id)
ttq.page()
}
+13 -3
View File
@@ -1,9 +1,19 @@
/**
* Analytics IDs, read from SiteIntegrations (public — safe on the client).
* Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe
* on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only
* after the matching consent category is granted (see Analytics).
*/
export type AnalyticsConfig = {
/** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. */
/** Microsoft Clarity project ID. (analytics consent) */
clarityProjectId?: null | string
/** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. (Google — Consent Mode) */
ga4MeasurementId?: null | string
/** GTM Container ID, e.g. 'GTM-XXXXXXX'. */
/** GTM Container ID, e.g. 'GTM-XXXXXXX'. (Google — Consent Mode) */
gtmContainerId?: null | string
/** LinkedIn Insight Tag partner ID. (marketing consent) */
linkedInPartnerId?: null | string
/** Meta (Facebook) Pixel ID, ~15–16 digits. (marketing consent) */
metaPixelId?: null | string
/** TikTok Pixel ID. (marketing consent) */
tiktokPixelId?: null | string
}
+1
View File
@@ -6,6 +6,7 @@ export { getArchiveEntries } from './getArchiveEntries.js'
export type { ArchiveEntries } from './getArchiveEntries.js'
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'
export { resolveNotFoundPage } from './resolveNotFoundPage.js'
export { resolveRedirect } from './resolveRedirect.js'
export { resolveRoute } from './resolveRoute.js'
export type { ResolvedRoute } from './resolveRoute.js'
@@ -0,0 +1,57 @@
import type { BasePayload } from 'payload'
type ResolveNotFoundPageArgs = {
locale: string
/** Client's Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
payload: BasePayload
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
}
/**
* Returns the page the editor assigned as **404 (Not Found)** in System Pages,
* fully populated (depth 2, same shape as resolveRoute's pages), or null when
* the role is unassigned.
*
* Used by the project's `not-found.tsx`. The editor decides what a 404 looks
* like: a dedicated "Not found" page, or simply the homepage. Null means
* "render the project's built-in fallback view".
*
* Never throws — a missing DB (container build prerendering not-found) or a
* deleted page just yields null, so the 404 view can't crash the build.
*/
export async function resolveNotFoundPage({
locale,
pagesSlug = 'pages',
payload,
settingsSlug = 'site-settings',
}: ResolveNotFoundPageArgs): Promise<null | Record<string, unknown>> {
try {
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 0,
locale: locale as never,
})) as Record<string, unknown>
const rel = settings.notFound
const id =
typeof rel === 'string' || typeof rel === 'number'
? rel
: rel && typeof rel === 'object'
? (rel as { id?: number | string }).id
: undefined
if (id === undefined) {return null}
const doc = await payload.findByID({
id,
collection: pagesSlug as never,
depth: 2,
locale: locale as never,
})
return (doc as null | Record<string, unknown>) ?? null
} catch (error) {
console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error)
return null
}
}
+17
View File
@@ -160,5 +160,22 @@ export async function resolveRoute({
const doc = found.docs[0]
if (!doc) {return null}
// The page assigned as 404 in System Pages must not be reachable as a normal
// 200 URL (/pl/strona-nie-znaleziona) — that's a soft-404 / duplicate. Treat
// it as not found, so the route calls notFound() and not-found.tsx renders
// that same page with a real 404 status. (If 404 = homepage, the homepage is
// served from the root branch above and never reaches here by its own slug
// in a way that matters — but guard anyway so we never hide the homepage.)
const notFound = settings.notFound
const homepage = settings.homepage
const notFoundId =
notFound && typeof notFound === 'object' ? (notFound as { id?: unknown }).id : notFound
const homepageId =
homepage && typeof homepage === 'object' ? (homepage as { id?: unknown }).id : homepage
const docId = (doc as { id?: unknown }).id
if (notFoundId != null && notFoundId === docId && notFoundId !== homepageId) {
return null
}
return { type: 'page', doc: doc as Record<string, unknown> }
}
+30 -2
View File
@@ -7,7 +7,11 @@ import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/in
import type { I18nConfig } from '../i18n/index.js'
import type { RobotsRules, SitemapEntry } from '../seo/index.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import {
getArchiveEntries,
resolveNotFoundPage,
resolveRoute as resolveRouteRaw,
} from '../content/index.js'
import { buildRobots, buildSitemapEntries } from '../seo/index.js'
type CreateContentHelpersArgs = {
@@ -96,6 +100,20 @@ export function createContentHelpers({
},
)
/**
* The page assigned as 404 in System Pages (or null → built-in fallback).
* For app/not-found.tsx; never throws. Locale comes from the x-locale header
* set by createProxy (not-found.tsx receives no params).
*/
const getNotFoundPage = cache(async (locale: string) => {
try {
const payload = await getCachedPayload()
return await resolveNotFoundPage({ locale, pagesSlug, payload, settingsSlug })
} catch {
return null // DB unreachable (container build) — fallback view
}
})
/** One page of a collection's entries, for an archive listing. */
const getEntries = cache(
async (
@@ -202,8 +220,16 @@ export function createContentHelpers({
// Home slug per locale, to exclude the homepage (it's the root, slug []).
const settings = (await payload
.findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never })
.catch(() => null)) as { homepage?: { id?: number | string; slug?: unknown } } | null
.catch(() => null)) as {
homepage?: { id?: number | string; slug?: unknown }
notFound?: { id?: number | string } | null
} | null
const homeId = settings?.homepage?.id
// The assigned 404 page renders via not-found.tsx, never as its own URL.
const notFoundId =
settings?.notFound?.id !== undefined && settings.notFound.id !== homeId
? settings.notFound.id
: undefined
const EXCLUDED = new Set(['404', '500', 'error', 'not-found'])
const params: Array<{ locale: string; slug: string[] } | { slug: string[] }> = []
@@ -228,6 +254,7 @@ export function createContentHelpers({
}>) {
// Draft filter in memory (safe whether or not the collection has drafts).
if (raw._status && raw._status !== 'published') {continue}
if (notFoundId !== undefined && raw.id === notFoundId) {continue}
// NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex
// page (privacy, cookies, terms) still needs to render — users reach it
@@ -286,6 +313,7 @@ export function createContentHelpers({
getCachedPayload,
getConfiguredLocales,
getEntries,
getNotFoundPage,
getSettings,
resolveRoute,
robots,
+3
View File
@@ -8,6 +8,7 @@ import { ALL_SYSTEM_PAGE_ROLES } from './types.js'
const ROLE_LABELS: Record<SystemPageRole, string> = {
cookiePolicy: 'Cookie Policy',
homepage: 'Homepage',
notFound: '404 (Not Found)',
privacyPolicy: 'Privacy Policy',
termsOfService: 'Terms of Service',
}
@@ -16,6 +17,8 @@ const ROLE_LABELS: Record<SystemPageRole, string> = {
const ROLE_DESCRIPTIONS: Record<SystemPageRole, string> = {
cookiePolicy: 'Page linked from the cookie consent banner.',
homepage: 'Page served at the locale root (e.g. /pl, /en).',
notFound:
'Page shown for unknown URLs (404). Pick a dedicated "Not found" page, or reuse the homepage. If left empty, the project falls back to its built-in not-found view.',
privacyPolicy: 'Page linked as the privacy policy.',
termsOfService: 'Page linked as the terms of service / site regulations.',
}
+3 -1
View File
@@ -2,13 +2,15 @@
* Built-in "system page" roles — documents from the client's Pages
* collection that the site references by function rather than by slug.
*/
export type SystemPageRole = 'cookiePolicy' | 'homepage' | 'privacyPolicy' | 'termsOfService'
export type SystemPageRole =
'cookiePolicy' | 'homepage' | 'notFound' | 'privacyPolicy' | 'termsOfService'
/**
* All system roles in a stable order (used when no subset is configured).
*/
export const ALL_SYSTEM_PAGE_ROLES: readonly SystemPageRole[] = [
'homepage',
'notFound',
'privacyPolicy',
'cookiePolicy',
'termsOfService',