612 lines
28 KiB
TypeScript
612 lines
28 KiB
TypeScript
import type { Config, Plugin } from 'payload'
|
|
|
|
import { deepMergeSimple } from 'payload/shared'
|
|
|
|
import type { ResolvedAdminMeta } from './modules/branding/adminMeta.js'
|
|
import type { IpalOptions, TotpPluginFactory } from './types.js'
|
|
|
|
import { buildCookieSettings } from './globals/CookieSettings/index.js'
|
|
import { migrateCookieSettingsSaveButton } from './globals/CookieSettings/migrateSaveButton.js'
|
|
import { buildNotifications } from './globals/Notifications/index.js'
|
|
import { applyGlobalOverrides } from './globals/overrides.js'
|
|
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
|
|
import { buildSiteSettings } from './globals/SiteSettings/index.js'
|
|
import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js'
|
|
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
|
|
import { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
|
|
import { buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js'
|
|
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
|
|
import { addCookieScannerTabs } from './modules/consent/scanner/adminTabs.js'
|
|
import { buildCookieApprovalEndpoints, COOKIE_APPROVAL_VIEW_PATH } from './modules/consent/scanner/approval.js'
|
|
import { buildCookieReviewCollection } from './modules/consent/scanner/collection.js'
|
|
import { buildCookieCrawlEndpoints } from './modules/consent/scanner/crawl/endpoints.js'
|
|
import { buildCookieCrawlGlobal } from './modules/consent/scanner/crawl/global.js'
|
|
import { buildCookieScanEndpoints } from './modules/consent/scanner/endpoint.js'
|
|
import { mergeCookieScanLabels } from './modules/consent/scanner/labels.js'
|
|
import { buildConstructionFields } from './modules/construction/fields.js'
|
|
import { buildArchiveFields } from './modules/content/index.js'
|
|
import { buildDoctorEndpoint } from './modules/doctor/status.js'
|
|
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
|
|
import { emailSettingsFields } from './modules/forms/emailLayout.js'
|
|
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
|
|
import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.js'
|
|
import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
|
|
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
|
|
import { buildSystemPagesFields } from './modules/pages/index.js'
|
|
import { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
|
|
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
|
|
import { buildIndexNowHook } from './modules/seo/indexNow.js'
|
|
import { searchSettingsFields } from './modules/seo/searchSettings.js'
|
|
import { migrateTitleSeparator } from './modules/seo/titleSeparator.js'
|
|
import { applyCollectionOverride } from './modules/shared/collectionOverride.js'
|
|
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
|
|
|
|
/** The admin provider @clocklimited/payload-2fa registers; ipal-kit swaps it (twoFactor.provider). */
|
|
const TOTP_PACKAGE_PROVIDER = '@clocklimited/payload-2fa/rsc#TOTPProvider'
|
|
|
|
/**
|
|
* IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { ipalKit } from 'ipal-kit'
|
|
*
|
|
* export default buildConfig({
|
|
* plugins: [
|
|
* ipalKit({
|
|
* i18n: {
|
|
* locales: [
|
|
* { code: 'pl', label: 'Polski' },
|
|
* { code: 'en', label: 'English' },
|
|
* ],
|
|
* defaultLocale: 'pl',
|
|
* },
|
|
* access: { authCollection: 'users' },
|
|
* }),
|
|
* ],
|
|
* })
|
|
* ```
|
|
*/
|
|
export const ipalKit = (options: IpalOptions): Plugin => {
|
|
// Validate eagerly — fail fast before Payload boots
|
|
validateI18nConfig(options.i18n)
|
|
|
|
return async (incomingConfig: Config): Promise<Config> => {
|
|
const config = await transform(incomingConfig)
|
|
// Disabled: schema stays (collections, globals, fields — so a Postgres
|
|
// migration doesn't drop the plugin's tables), behaviour goes: no plugin
|
|
// endpoints, onInit work or admin components. Returning the incoming
|
|
// config untouched used to drop the plugin's collections and globals.
|
|
if (options.enabled === false) {
|
|
return {
|
|
...config,
|
|
admin: { ...config.admin, components: incomingConfig.admin?.components },
|
|
endpoints: incomingConfig.endpoints,
|
|
onInit: incomingConfig.onInit,
|
|
}
|
|
}
|
|
return config
|
|
}
|
|
|
|
async function transform(incomingConfig: Config): Promise<Config> {
|
|
|
|
let config = { ...incomingConfig }
|
|
|
|
// Text written in one language fills the empty languages of the same field (cookie list, cookie review).
|
|
const fillDefaults = { 'cookie-review': ['purpose', 'retention'], 'cookie-settings': ['cookies.purpose', 'cookies.duration'] }
|
|
const fillLocales: Record<keyof typeof fillDefaults, string[]> =
|
|
options.fillEmptyLocales === false
|
|
? { 'cookie-review': [], 'cookie-settings': [] }
|
|
: { ...fillDefaults, ...(typeof options.fillEmptyLocales === 'object' ? options.fillEmptyLocales : {}) }
|
|
|
|
// --- auth collection: Payload adds its default `users` only AFTER plugins
|
|
// run (config sanitize), so roles and 2FA would have nothing to attach to,
|
|
// and a project without it crashes ("users is not a valid admin user
|
|
// collection"). Inject a plain auth collection when the project defines
|
|
// none — a project's own collection with that slug always wins.
|
|
const authSlug =
|
|
options.access?.authCollection ??
|
|
(options.twoFactor ? options.twoFactor.collectionSlug : undefined) ??
|
|
config.admin?.user ??
|
|
'users'
|
|
// With roles on it (access.authCollection), the injected collection is
|
|
// locked down: Payload's default lets ANY logged-in account read, edit
|
|
// (email, password), unlock or delete every other account — a plain 'user'
|
|
// could take over an admin. Admins manage everyone; others only themselves.
|
|
// access.authAccess overrides any of it; a project's own collection wins whole.
|
|
if (!(config.collections ?? []).some((c) => c.slug === authSlug)) {
|
|
const hasRoles = options.access?.authCollection === authSlug
|
|
config.collections = [
|
|
...(config.collections ?? []),
|
|
{
|
|
slug: authSlug,
|
|
...(hasRoles
|
|
? {
|
|
access: {
|
|
create: adminOnly,
|
|
delete: adminOnly,
|
|
read: adminOrSelf,
|
|
unlock: adminOnly,
|
|
update: adminOrSelf,
|
|
...options.access?.authAccess,
|
|
},
|
|
}
|
|
: {}),
|
|
admin: { useAsTitle: 'email' },
|
|
auth: true,
|
|
fields: [],
|
|
},
|
|
]
|
|
}
|
|
|
|
// --- custom admin route (e.g. '/its' instead of '/admin') ---
|
|
// Sets config.routes.admin; the project must move its app/(payload)/<route>/
|
|
// folder to match (plugin can't create files in the project's app/).
|
|
if (options.adminRoute) {
|
|
config.routes = { ...(config.routes ?? {}), admin: options.adminRoute }
|
|
}
|
|
|
|
// --- enforced 2FA (TOTP) via @clocklimited/payload-2fa ---
|
|
// Enforced by default (forceSetup) unless twoFactor is explicitly false. The
|
|
// package is an optional PEER the project injects — ipal-kit doesn't bundle
|
|
// or import it, so projects that opt out (twoFactor: false) needn't install it.
|
|
// Wrapping access control (not just admin UI) means TOTP gates data access —
|
|
// no API bypass.
|
|
if (options.twoFactor !== false) {
|
|
const tf = options.twoFactor
|
|
if (!tf?.issuer) {
|
|
throw new Error(
|
|
'[ipal] twoFactor.issuer is required (name shown in the authenticator ' +
|
|
'app). Pass twoFactor: { issuer: "Your Site" }, or twoFactor: false to ' +
|
|
'opt out (discouraged).',
|
|
)
|
|
}
|
|
// The project INJECTS the factory (twoFactor.plugin = payloadTotp) — the
|
|
// plugin never imports the optional peer itself, so Next has nothing it
|
|
// can't bundle. See TotpPluginFactory / docs/security.md.
|
|
const totp: TotpPluginFactory | undefined = tf.plugin
|
|
|
|
if (typeof totp !== 'function') {
|
|
throw new Error(
|
|
'[ipal] 2FA is enforced but no 2FA plugin was injected. Add ' +
|
|
'`import { payloadTotp } from "@clocklimited/payload-2fa"` and pass ' +
|
|
'`twoFactor: { issuer, plugin: payloadTotp }`. Or set twoFactor: false ' +
|
|
'to opt out (discouraged).',
|
|
)
|
|
}
|
|
|
|
// TOTP must wrap the collection people log in to the panel with
|
|
// (admin.user, else Payload's pick: the first auth collection). Wrapping
|
|
// another slug leaves the real one without TOTP fields, and the TOTP
|
|
// access wrapper lets users without those fields through — 2FA silently
|
|
// off. So: default to it, and refuse a target that isn't an auth
|
|
// collection, or differs from it unless allowCollectionMismatch says so.
|
|
const authSlugs = (config.collections ?? []).filter((c) => c.auth).map((c) => c.slug)
|
|
const adminSlug = config.admin?.user ?? authSlugs[0] ?? authSlug
|
|
const target = tf.collectionSlug ?? adminSlug
|
|
if (!authSlugs.includes(target)) {
|
|
throw new Error(
|
|
`[ipal] twoFactor: "${target}" is not an auth collection, so 2FA would protect nothing. ` +
|
|
`Auth collections: ${authSlugs.join(', ') || 'none'}. Fix twoFactor.collectionSlug.`,
|
|
)
|
|
}
|
|
if (target !== adminSlug && !tf.allowCollectionMismatch) {
|
|
throw new Error(
|
|
`[ipal] twoFactor wraps "${target}" but the admin panel logs in with "${adminSlug}" ` +
|
|
'(admin.user) — those accounts would skip 2FA. Point twoFactor.collectionSlug at ' +
|
|
`"${adminSlug}", or pass twoFactor.allowCollectionMismatch: true if that is deliberate.`,
|
|
)
|
|
}
|
|
config = await totp({
|
|
collection: target,
|
|
forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out
|
|
totp: { issuer: tf.issuer },
|
|
})(config)
|
|
|
|
// The package's texts are long and informal: ipal-kit's (admin-ux.md) go over
|
|
// them, the project's own i18n.translations over both. The 2FA screens get a
|
|
// tab title instead of "Payload" (view meta is a plain string: the site's language).
|
|
if (tf.texts !== false) {
|
|
config.i18n = {
|
|
...config.i18n,
|
|
translations: deepMergeSimple(
|
|
deepMergeSimple((config.i18n?.translations ?? {}) as Record<string, unknown>, TOTP_TEXTS),
|
|
(incomingConfig.i18n?.translations ?? {}) as Record<string, unknown>,
|
|
),
|
|
}
|
|
const title = TOTP_VIEW_TITLE[options.i18n.defaultLocale.toLowerCase().startsWith('pl') ? 'pl' : 'en']
|
|
const views = config.admin?.components?.views ?? {}
|
|
config.admin = {
|
|
...config.admin,
|
|
components: {
|
|
...config.admin?.components,
|
|
views: Object.fromEntries(
|
|
Object.entries(views).map(([key, view]) =>
|
|
/^(?:Setup|Verify)TOTP/.test(key) && view && !view.meta?.title
|
|
? [key, { ...view, meta: { ...view.meta, title } }]
|
|
: [key, view],
|
|
),
|
|
),
|
|
},
|
|
}
|
|
}
|
|
|
|
// The package's TOTPProvider reads the path from an `x-pathname` header
|
|
// no proxy sets on /admin, so it redirected the setup screen to itself
|
|
// (`setup-totp?back=null`). Swap in ipal-kit's client-side provider, or
|
|
// the project's (`provider`); `provider: false` keeps the package's.
|
|
if (tf.provider !== false) {
|
|
const custom = tf.provider
|
|
const ours =
|
|
typeof custom === 'object' ? custom : { path: custom ?? '@intecion/ipal-kit/admin#TotpRedirectProvider' }
|
|
const providers = config.admin?.components?.providers ?? []
|
|
config.admin = {
|
|
...config.admin,
|
|
components: {
|
|
...config.admin?.components,
|
|
providers: providers.map((p) =>
|
|
p && (typeof p === 'string' ? p : p.path) === TOTP_PACKAGE_PROVIDER
|
|
? {
|
|
...ours,
|
|
clientProps: { forceSetup: true, ...ours.clientProps },
|
|
serverProps: { ...(typeof p === 'object' ? p.serverProps : {}), ...ours.serverProps },
|
|
}
|
|
: p,
|
|
),
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
const agency = options.agency === undefined ? DEFAULT_AGENCY : options.agency
|
|
|
|
// --- white-label admin branding ---
|
|
// Inject admin.components.graphics.Logo/Icon pointing at the plugin's
|
|
// /admin export. The components read SiteSettings at render, so each client
|
|
// sees their own brand from the panel (no brand in code). Project must run
|
|
// `pnpm generate:importmap` so Payload resolves the component paths.
|
|
if (options.whiteLabel) {
|
|
const wl = options.whiteLabel === true ? {} : options.whiteLabel
|
|
const serverProps: Record<string, unknown> = {}
|
|
if (wl.settingsSlug) {serverProps.settingsSlug = wl.settingsSlug}
|
|
if (wl.nameField) {serverProps.nameField = wl.nameField}
|
|
const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }
|
|
const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }
|
|
|
|
// Vendor credit ("Technology by Intecion.com") under the nav — on by
|
|
// default, hidden with credit:false, text/url overridable.
|
|
const creditOn = wl.credit !== false && agency !== false
|
|
const creditProps = {
|
|
...(agency ? { agency: agency.name, url: agency.url } : {}),
|
|
...(wl.credit && typeof wl.credit === 'object'
|
|
? {
|
|
...(wl.credit.text ? { text: wl.credit.text } : {}),
|
|
...(wl.credit.url ? { url: wl.credit.url } : {}),
|
|
}
|
|
: {}),
|
|
}
|
|
|
|
config.admin = {
|
|
...(config.admin ?? {}),
|
|
components: {
|
|
...(config.admin?.components ?? {}),
|
|
graphics: {
|
|
...(config.admin?.components?.graphics ?? {}),
|
|
Icon: { path: '@intecion/ipal-kit/admin#AdminIcon', serverProps: iconProps },
|
|
Logo: { path: '@intecion/ipal-kit/admin#AdminLogo', serverProps: logoProps },
|
|
},
|
|
...(creditOn
|
|
? {
|
|
afterLogin: [
|
|
...(config.admin?.components?.afterLogin ?? []),
|
|
{
|
|
path: '@intecion/ipal-kit/admin#IntecionCredit',
|
|
serverProps: { ...creditProps, variant: 'login' },
|
|
},
|
|
],
|
|
afterNavLinks: [
|
|
...(config.admin?.components?.afterNavLinks ?? []),
|
|
{
|
|
path: '@intecion/ipal-kit/admin#IntecionCredit',
|
|
serverProps: { ...creditProps, variant: 'nav' },
|
|
},
|
|
],
|
|
}
|
|
: {}),
|
|
},
|
|
...(wl.titleSuffix
|
|
? { meta: { ...(config.admin?.meta ?? {}), titleSuffix: wl.titleSuffix } }
|
|
: {}),
|
|
}
|
|
}
|
|
|
|
// --- admin <head>: link previews + noindex (default on) ---
|
|
// Static parts now; the site name parts come from Site settings in onInit
|
|
// and after every save (syncAdminMeta). The project's own admin.meta keys win.
|
|
let adminMeta: null | ResolvedAdminMeta = null
|
|
const brandFields = options.whiteLabel && options.whiteLabel !== true ? options.whiteLabel : {}
|
|
const settingsSlug = brandFields.settingsSlug ?? 'site-settings'
|
|
if (options.adminMeta !== false) {
|
|
const built = buildAdminMeta({
|
|
agency,
|
|
apiRoute: config.routes?.api,
|
|
defaultLocale: options.i18n.defaultLocale,
|
|
meta: config.admin?.meta,
|
|
options: options.adminMeta ?? {},
|
|
})
|
|
adminMeta = built.resolved
|
|
config.admin = { ...(config.admin ?? {}), meta: built.meta }
|
|
config.endpoints = [
|
|
...(config.endpoints ?? []),
|
|
...buildAdminImageEndpoints(built.resolved, {
|
|
iconField: brandFields.iconField,
|
|
logoField: brandFields.logoField,
|
|
nameField: brandFields.nameField,
|
|
settingsSlug,
|
|
}),
|
|
]
|
|
}
|
|
|
|
// --- i18n ---
|
|
config.localization = buildLocalizationConfig(options.i18n)
|
|
// Admin languages (en + pl unless the project set its own) and the plugin's texts.
|
|
config = applyAdminI18n(config)
|
|
|
|
// --- access: inject roles into the client's auth collection ---
|
|
if (options.access) {
|
|
config = injectRoles(config, options.access)
|
|
}
|
|
|
|
// --- seo: apply @payloadcms/plugin-seo directly ---
|
|
// NOTE: apply the plugin function to the config immediately rather than
|
|
// pushing it onto config.plugins. Payload has already iterated the plugins
|
|
// array by the time IPAL runs, so nested plugins added to that list are
|
|
// never executed. Calling the plugin as (config) => config applies its
|
|
// transform now.
|
|
if (options.seo) {
|
|
config = await buildSeoPlugin({ seo: options.seo })(config)
|
|
// Auto-fill empty meta from document content on save
|
|
config = injectAutoFillMeta(config, options.seo)
|
|
// Wrap fields into Content + SEO tabs (replaces plugin-seo's tabbedUI,
|
|
// which breaks when other fields already exist in the collection)
|
|
config = injectSeoTabs(config, options.seo)
|
|
}
|
|
|
|
// --- theme: the localStorage key of the visitor's choice reaches getSiteShell() through config.custom ---
|
|
if (options.theme?.storageKey) {
|
|
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, themeStorageKey: options.theme.storageKey } }
|
|
}
|
|
|
|
// --- forms: apply @payloadcms/plugin-form-builder directly ---
|
|
if (options.forms) {
|
|
config = await buildFormsPlugin(options.forms)(config)
|
|
// submitForm reads it from payload.config when the call doesn't pass one
|
|
if (options.forms.consentFieldName) {
|
|
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, consentFieldName: options.forms.consentFieldName } }
|
|
}
|
|
}
|
|
|
|
// --- globals ---
|
|
// The System Pages tab collects every "which page plays this role"
|
|
// assignment. Composing it here keeps SiteSettings unaware of which modules
|
|
// are enabled — it just renders the fields it's given.
|
|
const systemPageFields = [
|
|
...(options.pages ? buildSystemPagesFields(options.pages) : []),
|
|
...(options.content && options.pages
|
|
? buildArchiveFields(options.content, options.pages.slug)
|
|
: []),
|
|
]
|
|
|
|
// Top-level option first (works without `seo`), then the older seo.searchSettings.
|
|
const searchSettings = options.searchSettings ?? options.seo?.searchSettings
|
|
const pluginGlobals = [
|
|
buildSiteSettings({
|
|
additionalFields: options.siteSettingsFields,
|
|
...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}),
|
|
...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}),
|
|
...(searchSettings === false
|
|
? {}
|
|
: { searchFields: typeof searchSettings === 'function' ? searchSettings(searchSettingsFields) : searchSettingsFields }),
|
|
systemPageFields,
|
|
}),
|
|
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
|
|
withFillLocales('global', buildCookieSettings(), fillLocales['cookie-settings']),
|
|
buildNotifications({ lightbox: options.lightbox === true }),
|
|
]
|
|
// A global feeds every page's layout — revalidate the site on save.
|
|
const revalidateGlobal = options.revalidatePath ? buildGlobalRevalidateHook({ revalidatePath: options.revalidatePath }) : null
|
|
const withRevalidate = revalidateGlobal
|
|
? pluginGlobals.map((g) => ({ ...g, hooks: { ...g.hooks, afterChange: [...(g.hooks?.afterChange ?? []), revalidateGlobal] } }))
|
|
: pluginGlobals
|
|
// The project's globalOverrides win (access, admin, hooks merged; a function = full control).
|
|
config.globals = [...(config.globals ?? []), ...applyGlobalOverrides(withRevalidate, options.globalOverrides)]
|
|
|
|
// A new site name refreshes the panel's link preview texts.
|
|
if (adminMeta) {
|
|
const resolved = adminMeta
|
|
config.globals = config.globals.map((g) =>
|
|
g.slug === settingsSlug
|
|
? {
|
|
...g,
|
|
hooks: {
|
|
...g.hooks,
|
|
afterChange: [
|
|
...(g.hooks?.afterChange ?? []),
|
|
async ({ doc, req }) => {
|
|
if (req?.payload) {await syncAdminMeta(req.payload, resolved, { nameField: brandFields.nameField, settingsSlug })}
|
|
return doc
|
|
},
|
|
],
|
|
},
|
|
}
|
|
: g,
|
|
)
|
|
}
|
|
|
|
config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint]
|
|
|
|
// --- ipal-doctor status (404 until IPAL_DOCTOR_TOKEN is set; docs/doctor.md) ---
|
|
if (options.doctor !== false) {
|
|
config.endpoints = [...(config.endpoints ?? []), buildDoctorEndpoint(options.doctor ?? {})]
|
|
}
|
|
|
|
// --- consent log: proof of consent (opt-in) ---
|
|
if (options.consentLog) {
|
|
const logOptions = options.consentLog === true ? {} : options.consentLog
|
|
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildConsentLogCollection(), logOptions.collectionOverrides)]
|
|
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
|
|
}
|
|
|
|
// --- cookie scanner: review list + "Scan cookies" (opt-in) ---
|
|
if (options.cookieScanner) {
|
|
const scannerOptions = options.cookieScanner === true ? {} : options.cookieScanner
|
|
const adminRoute = options.adminRoute ?? '/admin'
|
|
const labels = mergeCookieScanLabels(scannerOptions.labels)
|
|
// One "Cookies" entry by default: the review list and the site check leave the navigation
|
|
// (their pages and API stay) and appear as tabs of the Cookies global.
|
|
const combined = scannerOptions.adminLayout !== 'separate'
|
|
const hideFromNav = <T extends { admin?: object }>(entity: T): T => (combined ? { ...entity, admin: { ...entity.admin, group: false } } : entity)
|
|
config.collections = [
|
|
...(config.collections ?? []),
|
|
applyCollectionOverride(hideFromNav(withFillLocales('collection', buildCookieReviewCollection(scannerOptions), fillLocales['cookie-review'])), scannerOptions.collectionOverrides),
|
|
]
|
|
const scanPlugin = { localeCount: options.i18n.locales.length, stats: Boolean(options.stats), ...(options.theme?.storageKey ? { themeStorageKey: options.theme.storageKey } : {}) }
|
|
config.endpoints = [...(config.endpoints ?? []), ...buildCookieScanEndpoints(scannerOptions, scanPlugin)]
|
|
// One approval for everything found (default on): the "Approve cookies" view and its endpoint.
|
|
const approval = scannerOptions.approval === false ? null : (scannerOptions.approval ?? {})
|
|
if (approval) {
|
|
config.endpoints = [...(config.endpoints ?? []), ...buildCookieApprovalEndpoints(scannerOptions)]
|
|
config.admin = {
|
|
...(config.admin ?? {}),
|
|
components: {
|
|
...(config.admin?.components ?? {}),
|
|
views: {
|
|
...(config.admin?.components?.views ?? {}),
|
|
ipalCookieApproval: {
|
|
Component: {
|
|
path: '@intecion/ipal-kit/admin#CookieApprovalView',
|
|
serverProps: { adminRoute, labels, ...(approval.unknownCategory ? { unknownCategory: approval.unknownCategory } : {}) },
|
|
},
|
|
meta: { title: 'Approve cookies' },
|
|
path: COOKIE_APPROVAL_VIEW_PATH,
|
|
},
|
|
},
|
|
},
|
|
}
|
|
}
|
|
// Browser crawl through the scanner service (opt-in): latest-result global, endpoints.
|
|
const crawl = scannerOptions.crawl ? (scannerOptions.crawl === true ? {} : scannerOptions.crawl) : null
|
|
if (crawl) {
|
|
const crawlGlobal = hideFromNav(buildCookieCrawlGlobal(labels))
|
|
const override = crawl.globalOverride
|
|
config.globals = [
|
|
...(config.globals ?? []),
|
|
override ? applyGlobalOverrides([crawlGlobal], { [crawlGlobal.slug]: override } as never)[0] : crawlGlobal,
|
|
]
|
|
config.endpoints = [...(config.endpoints ?? []), ...buildCookieCrawlEndpoints({ labels, options: scannerOptions, plugin: scanPlugin })]
|
|
}
|
|
if (combined) {
|
|
config.globals = (config.globals ?? []).map((g) =>
|
|
g.slug === 'cookie-settings'
|
|
? addCookieScannerTabs(g, { approval: Boolean(approval), crawl: Boolean(crawl), labels, unknownCategory: approval?.unknownCategory })
|
|
: g,
|
|
)
|
|
}
|
|
// Dashboard warning: cookies waiting for approval, crawl violations or a failed crawl.
|
|
const alertApproval = Boolean(approval && approval.dashboard !== false)
|
|
const alertCrawl = Boolean(crawl && crawl.dashboard !== false)
|
|
if (alertApproval || alertCrawl) {
|
|
config.admin = {
|
|
...(config.admin ?? {}),
|
|
components: {
|
|
...(config.admin?.components ?? {}),
|
|
beforeDashboard: [
|
|
...(config.admin?.components?.beforeDashboard ?? []),
|
|
{ path: '@intecion/ipal-kit/admin#CookieCrawlAlert', serverProps: { adminRoute, approval: alertApproval, crawl: alertCrawl, labels } },
|
|
],
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- built-in statistics: cookieless visits + consented history (opt-in) ---
|
|
if (options.stats) {
|
|
const statsOptions = options.stats === true ? {} : options.stats
|
|
const adminRoute = options.adminRoute ?? '/admin'
|
|
const viewProps = { adminRoute, ...(statsOptions.timeZone ? { timeZone: statsOptions.timeZone } : {}) }
|
|
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildStatsCollection(), statsOptions.collectionOverrides)]
|
|
config.endpoints = [...(config.endpoints ?? []), buildStatsEndpoint(statsOptions)]
|
|
config.admin = {
|
|
...(config.admin ?? {}),
|
|
components: {
|
|
...(config.admin?.components ?? {}),
|
|
afterNavLinks: [
|
|
...(config.admin?.components?.afterNavLinks ?? []),
|
|
{ path: '@intecion/ipal-kit/admin#StatsNavLink', serverProps: { adminRoute } },
|
|
],
|
|
beforeDashboard: [
|
|
...(config.admin?.components?.beforeDashboard ?? []),
|
|
...(statsOptions.dashboard === false
|
|
? []
|
|
: [{ path: '@intecion/ipal-kit/admin#StatsWidget', serverProps: viewProps }]),
|
|
],
|
|
views: {
|
|
...(config.admin?.components?.views ?? {}),
|
|
ipalStats: {
|
|
Component: { path: '@intecion/ipal-kit/admin#StatsView', serverProps: viewProps },
|
|
meta: { title: 'Statistics' },
|
|
path: '/stats',
|
|
},
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
// --- IndexNow: submit published URLs (opt-in) ---
|
|
if (options.indexNow) {
|
|
const pagesSlug = options.pages?.slug ?? 'pages'
|
|
const contentSlugs = new Set((options.content?.collections ?? []).map((c) => c.slug))
|
|
config.collections = (config.collections ?? []).map((collection) => {
|
|
const isPages = collection.slug === pagesSlug
|
|
if (!isPages && !contentSlugs.has(collection.slug)) {return collection}
|
|
const hook = buildIndexNowHook({
|
|
config: options.i18n,
|
|
...(isPages ? {} : { contentCollection: collection.slug }),
|
|
})
|
|
return {
|
|
...collection,
|
|
hooks: { ...collection.hooks, afterChange: [...(collection.hooks?.afterChange ?? []), hook] },
|
|
}
|
|
})
|
|
}
|
|
|
|
// --- integration alerts on the dashboard (Turnstile status, …) ---
|
|
// Renders nothing while everything works; never throws.
|
|
config.admin = {
|
|
...(config.admin ?? {}),
|
|
components: {
|
|
...(config.admin?.components ?? {}),
|
|
beforeDashboard: [
|
|
...(config.admin?.components?.beforeDashboard ?? []),
|
|
{
|
|
path: '@intecion/ipal-kit/admin#IntegrationAlerts',
|
|
serverProps: { adminRoute: options.adminRoute ?? '/admin' },
|
|
},
|
|
],
|
|
},
|
|
}
|
|
|
|
// --- hooks: onInit ---
|
|
const incomingOnInit = config.onInit
|
|
config.onInit = async (payload) => {
|
|
if (incomingOnInit) {await incomingOnInit(payload)}
|
|
await migrateCookieSettingsSaveButton(payload)
|
|
await migrateTitleSeparator(payload, settingsSlug)
|
|
if (adminMeta) {await syncAdminMeta(payload, adminMeta, { nameField: brandFields.nameField, settingsSlug })}
|
|
payload.logger.info('[ipal] Plugin initialized.')
|
|
}
|
|
|
|
return config
|
|
}
|
|
}
|