Compare commits

..
36 Commits
Author SHA1 Message Date
radoslaw.smolinski 9b9bbc1a9f 1.6.3 2026-10-09 18:23:18 +02:00
radoslaw.smolinski abf2e7d40f Added form validators 2026-10-09 18:23:08 +02:00
radoslaw.smolinski d500d9412f 1.6.2 2026-10-09 18:00:32 +02:00
radoslaw.smolinski d034ddf990 Security patch for contact 2026-10-09 18:00:24 +02:00
radoslaw.smolinski 2dfacb0414 1.6.1 2026-10-09 17:25:28 +02:00
radoslaw.smolinski eb6efa26f6 Added JsonLdGraph.tsx 2026-10-09 17:25:22 +02:00
radoslaw.smolinski f5a4ceb5bf 1.6.0 2026-10-09 17:02:07 +02:00
radoslaw.smolinski d041fd4bc6 Added languageswitcher, alternatelinkscontext components support 2026-10-09 17:01:52 +02:00
radoslaw.smolinski e232e6d2a5 1.5.7 2026-10-09 16:44:39 +02:00
radoslaw.smolinski c738435fe0 Added richtext support, and helpers for proxy, llms route 2026-10-09 16:44:28 +02:00
radoslaw.smolinski cca2b20c3d 1.5.6 2026-09-28 19:44:34 +02:00
radoslaw.smolinski 105c454d73 Added OG support 2026-09-28 19:44:28 +02:00
radoslaw.smolinski cf6feefebc 1.5.5 2026-09-28 16:47:11 +02:00
radoslaw.smolinski 1857c8f771 Sitemap language normalize trough all websites 2026-09-28 16:47:06 +02:00
radoslaw.smolinski 542ad4ab9c 1.5.4 2026-09-28 16:35:00 +02:00
radoslaw.smolinski 9bf8599116 Fix for plugin.ts 2026-09-28 16:34:54 +02:00
radoslaw.smolinski 170c9a53f1 1.5.3 2026-09-28 16:25:36 +02:00
radoslaw.smolinski e0d5095099 Fix for sitemap.css n2 2026-09-28 16:22:49 +02:00
radoslaw.smolinski 08a8a10478 1.5.2 2026-09-28 16:13:46 +02:00
radoslaw.smolinski 7bbaf14d14 Fixed sitemap.css 2026-09-28 16:13:33 +02:00
radoslaw.smolinski b7d0b01122 1.5.1 2026-09-28 16:01:09 +02:00
radoslaw.smolinski 4627266577 2FA Fix 2026-09-28 16:01:03 +02:00
radoslaw.smolinski 471ec4b12a 1.5.0 2026-09-28 15:49:57 +02:00
radoslaw.smolinski 060a61fd41 Added secuirty 2FA for users 2026-09-28 15:49:36 +02:00
radoslaw.smolinski 7cef95225a 1.4.4 2026-09-28 14:57:54 +02:00
radoslaw.smolinski 0ae62226bc Path fix for sitemap css asset 2026-09-28 14:57:49 +02:00
radoslaw.smolinski 610ab6fdf5 1.4.3 2026-09-28 14:54:30 +02:00
radoslaw.smolinski 81275c0395 Added css asset for sitemap 2026-09-28 14:54:21 +02:00
radoslaw.smolinski 4a46651839 1.4.2 2026-09-28 14:47:19 +02:00
radoslaw.smolinski e7f06548fb Added styling for sitemap generator 2026-09-28 14:47:13 +02:00
radoslaw.smolinski e2a703fc72 1.4.1 2026-09-28 14:29:50 +02:00
radoslaw.smolinski de75d8374d Rebuilded sitemap generator 2026-09-28 14:29:42 +02:00
radoslaw.smolinski b807fbe69a 1.4.0 2026-09-26 22:30:13 +02:00
radoslaw.smolinski 827cd9bcbc Added accessibility support 2026-09-26 22:29:53 +02:00
radoslaw.smolinski fa2b607979 1.3.2 2026-09-26 20:07:35 +02:00
radoslaw.smolinski 4fe690e1e2 Added i18n exports 2026-09-26 20:07:29 +02:00
139 changed files with 4652 additions and 205 deletions
+12 -2
View File
@@ -1,5 +1,7 @@
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js';
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js';
export { AccessibilityProvider, AccessibilityWidget, useAccessibility, } from '../modules/accessibility/client.js';
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js';
export { Analytics } from '../modules/analytics/client.js';
/**
* Entry point: ipal-kit/client
@@ -10,8 +12,16 @@ export { Analytics } from '../modules/analytics/client.js';
*/
export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentContext, } from '../modules/consent/client.js';
export type { CookieBannerClassNames } from '../modules/consent/client.js';
export { resolveFormMessage } from '../modules/notifications/resolveFormMessage.js';
export type { FormNotificationTexts } from '../modules/notifications/types.js';
export { useContactForm } from '../modules/forms/useContactForm.js';
export type { ContactFormErrors, ContactFormValues, SubmitAction, } from '../modules/forms/useContactForm.js';
export { useForm } from '../modules/forms/useForm.js';
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js';
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from '../modules/forms/validators.js';
export type { Rule } from '../modules/forms/validators.js';
export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath, } from '../modules/i18n/index.js';
export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js';
export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks, } from '../modules/i18n/index.js';
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js';
export { Turnstile } from '../modules/turnstile/client.js';
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js';
export type { TurnstileProps } from '../modules/turnstile/client.js';
+8 -1
View File
@@ -1,6 +1,7 @@
'use client';
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js';
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js';
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js';
export { Analytics } from '../modules/analytics/client.js';
/**
* Entry point: ipal-kit/client
@@ -9,7 +10,13 @@ export { Analytics } from '../modules/analytics/client.js';
* components. Kept separate from the main entry so server bundles don't pull in
* client-only code.
*/ export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentContext } from '../modules/consent/client.js';
export { resolveFormMessage } from '../modules/notifications/resolveFormMessage.js';
export { useContactForm } from '../modules/forms/useContactForm.js';
export { useForm } from '../modules/forms/useForm.js';
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from '../modules/forms/validators.js';
// Pure i18n path helpers — no server/RSC deps, safe to import in client
// components (e.g. a LanguageSwitcher that computes locale URLs on the client).
export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath } from '../modules/i18n/index.js';
export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks } from '../modules/i18n/index.js';
export { Turnstile } from '../modules/turnstile/client.js';
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport { Analytics } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { resolveFormMessage } from '../modules/notifications/resolveFormMessage.js'\nexport type { FormNotificationTexts } from '../modules/notifications/types.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","Analytics","ConsentProvider","CookieBanner","CookieButton","useConsent","useConsentContext","resolveFormMessage","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SAASC,SAAS,QAAQ,iCAAgC;AAC1D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAErC,SAASC,kBAAkB,QAAQ,iDAAgD;AAEnF,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"}
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\n\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type {\n ContactFormErrors,\n ContactFormValues,\n SubmitAction,\n} from '../modules/forms/useContactForm.js'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from '../modules/forms/validators.js'\nexport type { Rule } from '../modules/forms/validators.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","ConsentProvider","CookieBanner","CookieButton","useConsent","useConsentContext","useContactForm","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAC1D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAGrC,SAASC,cAAc,QAAQ,qCAAoC;AAMnE,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,iCAAgC;AAEvC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"}
+1
View File
@@ -7,3 +7,4 @@
*/
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js';
export type { LocaleMiddlewareResult } from '../modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/index.js';
+1
View File
@@ -5,5 +5,6 @@
* client project's middleware.ts. Kept as a thin re-export so the Next-facing
* surface is separate from the main package export.
*/ export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/index.js';
//# sourceMappingURL=next-middleware.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../src/exports/next-middleware.ts"],"sourcesContent":["/**\n * Entry point: ipal-kit/next/middleware\n *\n * Re-exports the locale middleware factory and default matcher for use in a\n * client project's middleware.ts. Kept as a thin re-export so the Next-facing\n * surface is separate from the main package export.\n */\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from '../modules/i18n/index.js'\n"],"names":["createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,sBAAsB,EAAEC,0BAA0B,QAAQ,2BAA0B"}
{"version":3,"sources":["../../src/exports/next-middleware.ts"],"sourcesContent":["/**\n * Entry point: ipal-kit/next/middleware\n *\n * Re-exports the locale middleware factory and default matcher for use in a\n * client project's middleware.ts. Kept as a thin re-export so the Next-facing\n * surface is separate from the main package export.\n */\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from '../modules/i18n/index.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/index.js'\n"],"names":["createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","createProxy","DEFAULT_PROXY_MATCHER"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,sBAAsB,EAAEC,0BAA0B,QAAQ,2BAA0B;AAE7F,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,2BAA0B"}
+3
View File
@@ -7,4 +7,7 @@
*/
export { RenderBlocks } from '../modules/blocks/index.js';
export type { BlockComponentMap, BlockData, EnhanceProps, RenderBlocksProps, } from '../modules/blocks/index.js';
export { RenderRichText } from '../modules/richtext/index.js';
export type { RenderRichTextProps } from '../modules/richtext/index.js';
export { JsonLdGraph } from '../modules/seo/index.js';
export { MediaPreconnect } from '../modules/storage/MediaPreconnect.js';
+2
View File
@@ -5,6 +5,8 @@
* lives here rather than in the main package entry to keep React out of the
* server-config bundle.
*/ export { RenderBlocks } from '../modules/blocks/index.js';
export { RenderRichText } from '../modules/richtext/index.js';
export { JsonLdGraph } from '../modules/seo/index.js';
export { MediaPreconnect } from '../modules/storage/MediaPreconnect.js';
//# sourceMappingURL=rsc.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../src/exports/rsc.ts"],"sourcesContent":["/**\n * Entry point: ipal-kit/rsc\n *\n * Server-component exports. RenderBlocks is a React Server Component, so it\n * lives here rather than in the main package entry to keep React out of the\n * server-config bundle.\n */\nexport { RenderBlocks } from '../modules/blocks/index.js'\nexport type {\n BlockComponentMap,\n BlockData,\n EnhanceProps,\n RenderBlocksProps,\n} from '../modules/blocks/index.js'\nexport { MediaPreconnect } from '../modules/storage/MediaPreconnect.js'\n"],"names":["RenderBlocks","MediaPreconnect"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,YAAY,QAAQ,6BAA4B;AAOzD,SAASC,eAAe,QAAQ,wCAAuC"}
{"version":3,"sources":["../../src/exports/rsc.ts"],"sourcesContent":["/**\n * Entry point: ipal-kit/rsc\n *\n * Server-component exports. RenderBlocks is a React Server Component, so it\n * lives here rather than in the main package entry to keep React out of the\n * server-config bundle.\n */\nexport { RenderBlocks } from '../modules/blocks/index.js'\nexport type {\n BlockComponentMap,\n BlockData,\n EnhanceProps,\n RenderBlocksProps,\n} from '../modules/blocks/index.js'\nexport { RenderRichText } from '../modules/richtext/index.js'\nexport type { RenderRichTextProps } from '../modules/richtext/index.js'\nexport { JsonLdGraph } from '../modules/seo/index.js'\nexport { MediaPreconnect } from '../modules/storage/MediaPreconnect.js'\n"],"names":["RenderBlocks","RenderRichText","JsonLdGraph","MediaPreconnect"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,YAAY,QAAQ,6BAA4B;AAOzD,SAASC,cAAc,QAAQ,+BAA8B;AAE7D,SAASC,WAAW,QAAQ,0BAAyB;AACrD,SAASC,eAAe,QAAQ,wCAAuC"}
+9 -1
View File
@@ -1,5 +1,7 @@
export type { AccessOption, Role } from './modules/access/index.js';
export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSelf, authenticated, hasMinimumRole, isAdmin, isEditor, requireRole, requireRoleField, ROLE_HIERARCHY, } from './modules/access/index.js';
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y, } from './modules/accessibility/index.js';
export type { A11yState } from './modules/accessibility/index.js';
export type { AnalyticsConfig } from './modules/analytics/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';
@@ -15,12 +17,17 @@ export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js';
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption, } from './modules/forms/types.js';
export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js';
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from './modules/forms/validators.js';
export type { Rule } from './modules/forms/validators.js';
export { createContentHelpers } from './modules/frontend/index.js';
export { buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook, } from './modules/hooks/index.js';
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js';
export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath, } from './modules/i18n/index.js';
export type { LocaleMiddlewareResult } from './modules/i18n/index.js';
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
export { resolveLocalized } from './modules/i18n/index.js';
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js';
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage, } from './modules/notifications/index.js';
export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js';
@@ -36,12 +43,13 @@ export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js';
export { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js';
export type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js';
export { buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta, } from './modules/seo/index.js';
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler, } from './modules/seo/index.js';
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField, } from './modules/seo/index.js';
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd, } from './modules/seo/index.js';
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd, } from './modules/seo/index.js';
export { buildArticleJsonLd } from './modules/seo/index.js';
export { buildSitemapXml } from './modules/seo/index.js';
export { buildLlmsTxt } from './modules/seo/index.js';
export { buildSitemapXml } from './modules/seo/index.js';
export { buildSlugField, toSlug } from './modules/slug/index.js';
export { buildR2Storage } from './modules/storage/index.js';
export { ipalKit } from './plugin.js';
+9 -1
View File
@@ -1,4 +1,5 @@
export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSelf, authenticated, hasMinimumRole, isAdmin, isEditor, requireRole, requireRoleField, ROLE_HIERARCHY } from './modules/access/index.js';
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, buildArchivePath, buildEntryPath, getArchiveEntries, parsePageParam, resolveRoute } from './modules/content/index.js';
@@ -9,10 +10,16 @@ export { mailAdapter } from './modules/email/mailAdapter.js';
// Payload loads the config (or runs generate:importmap) as a plain Node script.
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
// Validation rules are pure — exported server-side too, for re-validating a
// submission inside a server action. (useForm/useContactForm are client-only →
// '@intecion/ipal-kit/client'.)
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from './modules/forms/validators.js';
export { createContentHelpers } from './modules/frontend/index.js';
export { buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js';
export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath } from './modules/i18n/index.js';
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
export { resolveLocalized } from './modules/i18n/index.js';
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js';
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js';
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js';
@@ -21,13 +28,14 @@ export { buildSecurityHeaders } from './modules/security/index.js';
export { buildCsp } from './modules/security/index.js';
export { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js';
export { buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta } from './modules/seo/index.js';
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler } from './modules/seo/index.js';
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js';
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js';
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js';
export { buildArticleJsonLd } from './modules/seo/index.js';
export { buildSitemapXml } from './modules/seo/index.js';
export { buildLlmsTxt } from './modules/seo/index.js';
export { buildSitemapXml } from './modules/seo/index.js';
export { buildSlugField, toSlug } from './modules/slug/index.js';
export { buildR2Storage } from './modules/storage/index.js';
export { ipalKit } from './plugin.js';
+1 -1
View File
File diff suppressed because one or more lines are too long
+29
View File
@@ -0,0 +1,29 @@
import { type A11yState } from './state.js';
type A11yContextValue = {
reset: () => void;
set: <K extends keyof A11yState>(key: K, value: A11yState[K]) => void;
state: A11yState;
};
/**
* Provides accessibility preferences, persists them in a cookie, and applies them
* as data-attributes on <html> so the project's CSS can react. Like
* ConsentProvider for cookies — wrap the app once; the widget/button consume it.
*
* The plugin ships NO styles: it only sets attributes (data-a11y-*). The project
* writes CSS for those it supports (see docs/accessibility.md). This keeps the
* design in the project's hands.
*
* // layout.tsx
* import { AccessibilityProvider } from '@intecion/ipal-kit/client'
* <AccessibilityProvider>{children}</AccessibilityProvider>
*
* To avoid a flash, the project can read the a11y-prefs cookie server-side and
* set the attributes on <html> during SSR (see docs). This provider re-applies
* on the client and keeps them in sync.
*/
export declare function AccessibilityProvider({ children }: {
children: React.ReactNode;
}): import("react/jsx-runtime").JSX.Element;
/** Access accessibility preferences + setters. Use inside AccessibilityProvider. */
export declare function useAccessibility(): A11yContextValue;
export {};
+87
View File
@@ -0,0 +1,87 @@
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, use, useCallback, useEffect, useState } from 'react';
import { A11Y_COOKIE, A11Y_COOKIE_MAX_AGE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './state.js';
const A11yContext = /*#__PURE__*/ createContext(null);
function readCookie(name) {
if (typeof document === 'undefined') {
return undefined;
}
const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
return match ? decodeURIComponent(match[1]) : undefined;
}
/**
* Provides accessibility preferences, persists them in a cookie, and applies them
* as data-attributes on <html> so the project's CSS can react. Like
* ConsentProvider for cookies — wrap the app once; the widget/button consume it.
*
* The plugin ships NO styles: it only sets attributes (data-a11y-*). The project
* writes CSS for those it supports (see docs/accessibility.md). This keeps the
* design in the project's hands.
*
* // layout.tsx
* import { AccessibilityProvider } from '@intecion/ipal-kit/client'
* <AccessibilityProvider>{children}</AccessibilityProvider>
*
* To avoid a flash, the project can read the a11y-prefs cookie server-side and
* set the attributes on <html> during SSR (see docs). This provider re-applies
* on the client and keeps them in sync.
*/ export function AccessibilityProvider({ children }) {
const [state, setState] = useState(A11Y_DEFAULT);
// Hydrate from cookie on mount.
useEffect(()=>{
setState(parseA11y(readCookie(A11Y_COOKIE)));
}, []);
// Apply attributes to <html> whenever state changes.
useEffect(()=>{
const el = document.documentElement;
const attrs = a11yAttributes(state);
for (const [attr, value] of Object.entries(attrs)){
if (value === null) {
el.removeAttribute(attr);
} else {
el.setAttribute(attr, value);
}
}
}, [
state
]);
const persist = useCallback((next)=>{
document.cookie = `${A11Y_COOKIE}=${encodeURIComponent(serializeA11y(next))}; path=/; max-age=${A11Y_COOKIE_MAX_AGE}; samesite=lax`;
}, []);
const set = useCallback((key, value)=>{
setState((prev)=>{
const next = {
...prev,
[key]: value
};
persist(next);
return next;
});
}, [
persist
]);
const reset = useCallback(()=>{
setState(A11Y_DEFAULT);
persist(A11Y_DEFAULT);
}, [
persist
]);
return /*#__PURE__*/ _jsx(A11yContext, {
value: {
reset,
set,
state
},
children: children
});
}
/** Access accessibility preferences + setters. Use inside AccessibilityProvider. */ export function useAccessibility() {
const ctx = use(A11yContext);
if (!ctx) {
throw new Error('useAccessibility must be used within <AccessibilityProvider>');
}
return ctx;
}
//# sourceMappingURL=AccessibilityProvider.js.map
File diff suppressed because one or more lines are too long
+41
View File
@@ -0,0 +1,41 @@
export type A11yTexts = {
bigCursor?: string;
close?: string;
contrast?: string;
contrastHigh?: string;
contrastInverted?: string;
grayscale?: string;
lineHeight?: string;
open?: string;
readableFont?: string;
reduceMotion?: string;
reset?: string;
textSize?: string;
title?: string;
underlineLinks?: string;
};
export type A11yClassNames = {
active?: string;
button?: string;
closeButton?: string;
control?: string;
label?: string;
panel?: string;
resetButton?: string;
row?: string;
};
/**
* Accessibility toolbar: a floating button that opens a panel of options (text
* size, line height, contrast, grayscale, underline links, readable font, reduce
* motion, big cursor). Choices persist in a cookie and apply as data-attributes
* on <html> (the project's CSS styles them).
*
* Unstyled by default — pass classNames to match the project's design (like
* CookieBanner). Wrap the app in <AccessibilityProvider> first.
*
* <AccessibilityWidget classNames={{ button: 'a11y-btn', panel: 'a11y-panel' }} />
*/
export declare function AccessibilityWidget({ classNames, texts, }: {
classNames?: A11yClassNames;
texts?: A11yTexts;
}): import("react/jsx-runtime").JSX.Element;
+188
View File
@@ -0,0 +1,188 @@
'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState } from 'react';
import { useAccessibility } from './AccessibilityProvider.js';
const DEFAULT_TEXTS = {
bigCursor: 'Duży kursor',
close: 'Zamknij',
contrast: 'Kontrast',
contrastHigh: 'Wysoki',
contrastInverted: 'Odwrócony',
grayscale: 'Skala szarości',
lineHeight: 'Odstęp między liniami',
open: 'Otwórz panel dostępności',
readableFont: 'Czytelna czcionka',
reduceMotion: 'Wyłącz animacje',
reset: 'Resetuj',
textSize: 'Rozmiar tekstu',
title: 'Dostępność',
underlineLinks: 'Podkreśl linki'
};
/**
* Accessibility toolbar: a floating button that opens a panel of options (text
* size, line height, contrast, grayscale, underline links, readable font, reduce
* motion, big cursor). Choices persist in a cookie and apply as data-attributes
* on <html> (the project's CSS styles them).
*
* Unstyled by default — pass classNames to match the project's design (like
* CookieBanner). Wrap the app in <AccessibilityProvider> first.
*
* <AccessibilityWidget classNames={{ button: 'a11y-btn', panel: 'a11y-panel' }} />
*/ export function AccessibilityWidget({ classNames, texts }) {
const { reset, set, state } = useAccessibility();
const [open, setOpen] = useState(false);
const t = {
...DEFAULT_TEXTS,
...texts
};
const cn = classNames ?? {};
const toggle = (key)=>set(key, !state[key]);
const isActive = (on)=>on ? cn.active ?? '' : '';
return /*#__PURE__*/ _jsxs(_Fragment, {
children: [
/*#__PURE__*/ _jsx("button", {
"aria-expanded": open,
"aria-label": t.open,
className: cn.button,
onClick: ()=>setOpen((o)=>!o),
type: "button",
children: /*#__PURE__*/ _jsx("span", {
"aria-hidden": "true",
children: "♿"
})
}),
open && /*#__PURE__*/ _jsxs("div", {
"aria-label": t.title,
className: cn.panel,
role: "dialog",
children: [
/*#__PURE__*/ _jsxs("div", {
className: cn.row,
children: [
/*#__PURE__*/ _jsx("span", {
className: cn.label,
children: t.textSize
}),
/*#__PURE__*/ _jsx("div", {
className: cn.control,
children: [
0,
1,
2,
3
].map((n)=>/*#__PURE__*/ _jsxs("button", {
className: isActive(state.textSize === n),
onClick: ()=>set('textSize', n),
type: "button",
children: [
"A",
n > 0 ? '+'.repeat(n) : ''
]
}, n))
})
]
}),
/*#__PURE__*/ _jsxs("div", {
className: cn.row,
children: [
/*#__PURE__*/ _jsx("span", {
className: cn.label,
children: t.lineHeight
}),
/*#__PURE__*/ _jsx("div", {
className: cn.control,
children: [
0,
1,
2
].map((n)=>/*#__PURE__*/ _jsx("button", {
className: isActive(state.lineHeight === n),
onClick: ()=>set('lineHeight', n),
type: "button",
children: n === 0 ? '—' : '≡'.repeat(n)
}, n))
})
]
}),
/*#__PURE__*/ _jsxs("div", {
className: cn.row,
children: [
/*#__PURE__*/ _jsx("span", {
className: cn.label,
children: t.contrast
}),
/*#__PURE__*/ _jsxs("div", {
className: cn.control,
children: [
/*#__PURE__*/ _jsx("button", {
className: isActive(state.contrast === 'high'),
onClick: ()=>set('contrast', state.contrast === 'high' ? 'default' : 'high'),
type: "button",
children: t.contrastHigh
}),
/*#__PURE__*/ _jsx("button", {
className: isActive(state.contrast === 'inverted'),
onClick: ()=>set('contrast', state.contrast === 'inverted' ? 'default' : 'inverted'),
type: "button",
children: t.contrastInverted
})
]
})
]
}),
[
[
'grayscale',
t.grayscale
],
[
'underlineLinks',
t.underlineLinks
],
[
'readableFont',
t.readableFont
],
[
'reduceMotion',
t.reduceMotion
],
[
'bigCursor',
t.bigCursor
]
].map(([key, label])=>/*#__PURE__*/ _jsxs("div", {
className: cn.row,
children: [
/*#__PURE__*/ _jsx("span", {
className: cn.label,
children: label
}),
/*#__PURE__*/ _jsx("button", {
"aria-pressed": Boolean(state[key]),
className: `${cn.control ?? ''} ${isActive(Boolean(state[key]))}`,
onClick: ()=>toggle(key),
type: "button",
children: state[key] ? 'ON' : 'OFF'
})
]
}, key)),
/*#__PURE__*/ _jsx("button", {
className: cn.resetButton,
onClick: reset,
type: "button",
children: t.reset
}),
/*#__PURE__*/ _jsx("button", {
className: cn.closeButton,
onClick: ()=>setOpen(false),
type: "button",
children: t.close
})
]
})
]
});
}
//# sourceMappingURL=AccessibilityWidget.js.map
File diff suppressed because one or more lines are too long
+5
View File
@@ -0,0 +1,5 @@
export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js';
export { AccessibilityWidget } from './AccessibilityWidget.js';
export type { A11yClassNames, A11yTexts } from './AccessibilityWidget.js';
export type { A11yState } from './state.js';
export { A11Y_COOKIE, a11yAttributes, parseA11y } from './state.js';
+6
View File
@@ -0,0 +1,6 @@
'use client';
export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js';
export { AccessibilityWidget } from './AccessibilityWidget.js';
export { A11Y_COOKIE, a11yAttributes, parseA11y } from './state.js';
//# sourceMappingURL=client.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/accessibility/client.ts"],"sourcesContent":["'use client'\nexport { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js'\nexport { AccessibilityWidget } from './AccessibilityWidget.js'\nexport type { A11yClassNames, A11yTexts } from './AccessibilityWidget.js'\nexport type { A11yState } from './state.js'\nexport { A11Y_COOKIE, a11yAttributes, parseA11y } from './state.js'\n"],"names":["AccessibilityProvider","useAccessibility","AccessibilityWidget","A11Y_COOKIE","a11yAttributes","parseA11y"],"mappings":"AAAA;AACA,SAASA,qBAAqB,EAAEC,gBAAgB,QAAQ,6BAA4B;AACpF,SAASC,mBAAmB,QAAQ,2BAA0B;AAG9D,SAASC,WAAW,EAAEC,cAAc,EAAEC,SAAS,QAAQ,aAAY"}
+5
View File
@@ -0,0 +1,5 @@
export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js';
export { AccessibilityWidget } from './AccessibilityWidget.js';
export type { A11yClassNames, A11yTexts } from './AccessibilityWidget.js';
export { A11Y_COOKIE, A11Y_COOKIE_MAX_AGE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y, } from './state.js';
export type { A11yState } from './state.js';
+5
View File
@@ -0,0 +1,5 @@
export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js';
export { AccessibilityWidget } from './AccessibilityWidget.js';
export { A11Y_COOKIE, A11Y_COOKIE_MAX_AGE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './state.js';
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/accessibility/index.ts"],"sourcesContent":["export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js'\nexport { AccessibilityWidget } from './AccessibilityWidget.js'\nexport type { A11yClassNames, A11yTexts } from './AccessibilityWidget.js'\nexport {\n A11Y_COOKIE,\n A11Y_COOKIE_MAX_AGE,\n A11Y_DEFAULT,\n a11yAttributes,\n parseA11y,\n serializeA11y,\n} from './state.js'\nexport type { A11yState } from './state.js'\n"],"names":["AccessibilityProvider","useAccessibility","AccessibilityWidget","A11Y_COOKIE","A11Y_COOKIE_MAX_AGE","A11Y_DEFAULT","a11yAttributes","parseA11y","serializeA11y"],"mappings":"AAAA,SAASA,qBAAqB,EAAEC,gBAAgB,QAAQ,6BAA4B;AACpF,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SACEC,WAAW,EACXC,mBAAmB,EACnBC,YAAY,EACZC,cAAc,EACdC,SAAS,EACTC,aAAa,QACR,aAAY"}
+37
View File
@@ -0,0 +1,37 @@
/**
* Accessibility preferences state. Each option maps to a data-attribute on
* <html> (e.g. data-a11y-contrast="high"); the PROJECT's CSS reacts to those
* attributes. The plugin sets the attributes and persists the choice — it does
* NOT ship styles, so it never fights the project's design.
*/
export type A11yState = {
/** Larger cursor. */
bigCursor: boolean;
/** 'default' | 'high' (high contrast) | 'inverted' (dark-on-light flip). */
contrast: 'default' | 'high' | 'inverted';
/** Grayscale filter on the whole page. */
grayscale: boolean;
/** Line spacing: 0 = default, 1..2 = looser. */
lineHeight: 0 | 1 | 2;
/** Readable font (project maps this to a dyslexia-friendly / simple font). */
readableFont: boolean;
/** Stop animations / transitions (prefers-reduced-motion equivalent). */
reduceMotion: boolean;
/** Text size step: 0 = default, 1..3 = larger. */
textSize: 0 | 1 | 2 | 3;
/** Underline all links (WCAG: don't rely on color alone). */
underlineLinks: boolean;
};
export declare const A11Y_DEFAULT: A11yState;
export declare const A11Y_COOKIE = "a11y-prefs";
export declare const A11Y_COOKIE_MAX_AGE: number;
/** Serialize for the cookie (compact). */
export declare function serializeA11y(state: A11yState): string;
/** Parse from the cookie; falls back to defaults on any bad value. */
export declare function parseA11y(raw: null | string | undefined): A11yState;
/**
* Maps state → data-attributes to set on <html>. Returns { attr: value|null };
* null means remove the attribute (option is at default). The project's CSS
* targets these, e.g. `[data-a11y-contrast="high"] { … }`.
*/
export declare function a11yAttributes(state: A11yState): Record<string, null | string>;
+53
View File
@@ -0,0 +1,53 @@
/**
* Accessibility preferences state. Each option maps to a data-attribute on
* <html> (e.g. data-a11y-contrast="high"); the PROJECT's CSS reacts to those
* attributes. The plugin sets the attributes and persists the choice — it does
* NOT ship styles, so it never fights the project's design.
*/ export const A11Y_DEFAULT = {
bigCursor: false,
contrast: 'default',
grayscale: false,
lineHeight: 0,
readableFont: false,
reduceMotion: false,
textSize: 0,
underlineLinks: false
};
export const A11Y_COOKIE = 'a11y-prefs';
export const A11Y_COOKIE_MAX_AGE = 60 * 60 * 24 * 365 // 1 year
;
/** Serialize for the cookie (compact). */ export function serializeA11y(state) {
return JSON.stringify(state);
}
/** Parse from the cookie; falls back to defaults on any bad value. */ export function parseA11y(raw) {
if (!raw) {
return A11Y_DEFAULT;
}
try {
const parsed = JSON.parse(raw);
return {
...A11Y_DEFAULT,
...parsed
};
} catch {
return A11Y_DEFAULT;
}
}
/**
* Maps state → data-attributes to set on <html>. Returns { attr: value|null };
* null means remove the attribute (option is at default). The project's CSS
* targets these, e.g. `[data-a11y-contrast="high"] { … }`.
*/ export function a11yAttributes(state) {
return {
'data-a11y-contrast': state.contrast !== 'default' ? state.contrast : null,
'data-a11y-cursor': state.bigCursor ? 'big' : null,
'data-a11y-font': state.readableFont ? 'readable' : null,
'data-a11y-grayscale': state.grayscale ? 'on' : null,
'data-a11y-line': state.lineHeight > 0 ? String(state.lineHeight) : null,
'data-a11y-motion': state.reduceMotion ? 'reduce' : null,
'data-a11y-text': state.textSize > 0 ? String(state.textSize) : null,
'data-a11y-underline': state.underlineLinks ? 'on' : null
};
}
//# sourceMappingURL=state.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/accessibility/state.ts"],"sourcesContent":["/**\n * Accessibility preferences state. Each option maps to a data-attribute on\n * <html> (e.g. data-a11y-contrast=\"high\"); the PROJECT's CSS reacts to those\n * attributes. The plugin sets the attributes and persists the choice — it does\n * NOT ship styles, so it never fights the project's design.\n */\nexport type A11yState = {\n /** Larger cursor. */\n bigCursor: boolean\n /** 'default' | 'high' (high contrast) | 'inverted' (dark-on-light flip). */\n contrast: 'default' | 'high' | 'inverted'\n /** Grayscale filter on the whole page. */\n grayscale: boolean\n /** Line spacing: 0 = default, 1..2 = looser. */\n lineHeight: 0 | 1 | 2\n /** Readable font (project maps this to a dyslexia-friendly / simple font). */\n readableFont: boolean\n /** Stop animations / transitions (prefers-reduced-motion equivalent). */\n reduceMotion: boolean\n /** Text size step: 0 = default, 1..3 = larger. */\n textSize: 0 | 1 | 2 | 3\n /** Underline all links (WCAG: don't rely on color alone). */\n underlineLinks: boolean\n}\n\nexport const A11Y_DEFAULT: A11yState = {\n bigCursor: false,\n contrast: 'default',\n grayscale: false,\n lineHeight: 0,\n readableFont: false,\n reduceMotion: false,\n textSize: 0,\n underlineLinks: false,\n}\n\nexport const A11Y_COOKIE = 'a11y-prefs'\nexport const A11Y_COOKIE_MAX_AGE = 60 * 60 * 24 * 365 // 1 year\n\n/** Serialize for the cookie (compact). */\nexport function serializeA11y(state: A11yState): string {\n return JSON.stringify(state)\n}\n\n/** Parse from the cookie; falls back to defaults on any bad value. */\nexport function parseA11y(raw: null | string | undefined): A11yState {\n if (!raw) {return A11Y_DEFAULT}\n try {\n const parsed = JSON.parse(raw) as Partial<A11yState>\n return { ...A11Y_DEFAULT, ...parsed }\n } catch {\n return A11Y_DEFAULT\n }\n}\n\n/**\n * Maps state → data-attributes to set on <html>. Returns { attr: value|null };\n * null means remove the attribute (option is at default). The project's CSS\n * targets these, e.g. `[data-a11y-contrast=\"high\"] { … }`.\n */\nexport function a11yAttributes(state: A11yState): Record<string, null | string> {\n return {\n 'data-a11y-contrast': state.contrast !== 'default' ? state.contrast : null,\n 'data-a11y-cursor': state.bigCursor ? 'big' : null,\n 'data-a11y-font': state.readableFont ? 'readable' : null,\n 'data-a11y-grayscale': state.grayscale ? 'on' : null,\n 'data-a11y-line': state.lineHeight > 0 ? String(state.lineHeight) : null,\n 'data-a11y-motion': state.reduceMotion ? 'reduce' : null,\n 'data-a11y-text': state.textSize > 0 ? String(state.textSize) : null,\n 'data-a11y-underline': state.underlineLinks ? 'on' : null,\n }\n}\n"],"names":["A11Y_DEFAULT","bigCursor","contrast","grayscale","lineHeight","readableFont","reduceMotion","textSize","underlineLinks","A11Y_COOKIE","A11Y_COOKIE_MAX_AGE","serializeA11y","state","JSON","stringify","parseA11y","raw","parsed","parse","a11yAttributes","String"],"mappings":"AAAA;;;;;CAKC,GAoBD,OAAO,MAAMA,eAA0B;IACrCC,WAAW;IACXC,UAAU;IACVC,WAAW;IACXC,YAAY;IACZC,cAAc;IACdC,cAAc;IACdC,UAAU;IACVC,gBAAgB;AAClB,EAAC;AAED,OAAO,MAAMC,cAAc,aAAY;AACvC,OAAO,MAAMC,sBAAsB,KAAK,KAAK,KAAK,IAAI,SAAS;CAAV;AAErD,wCAAwC,GACxC,OAAO,SAASC,cAAcC,KAAgB;IAC5C,OAAOC,KAAKC,SAAS,CAACF;AACxB;AAEA,oEAAoE,GACpE,OAAO,SAASG,UAAUC,GAA8B;IACtD,IAAI,CAACA,KAAK;QAAC,OAAOhB;IAAY;IAC9B,IAAI;QACF,MAAMiB,SAASJ,KAAKK,KAAK,CAACF;QAC1B,OAAO;YAAE,GAAGhB,YAAY;YAAE,GAAGiB,MAAM;QAAC;IACtC,EAAE,OAAM;QACN,OAAOjB;IACT;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASmB,eAAeP,KAAgB;IAC7C,OAAO;QACL,sBAAsBA,MAAMV,QAAQ,KAAK,YAAYU,MAAMV,QAAQ,GAAG;QACtE,oBAAoBU,MAAMX,SAAS,GAAG,QAAQ;QAC9C,kBAAkBW,MAAMP,YAAY,GAAG,aAAa;QACpD,uBAAuBO,MAAMT,SAAS,GAAG,OAAO;QAChD,kBAAkBS,MAAMR,UAAU,GAAG,IAAIgB,OAAOR,MAAMR,UAAU,IAAI;QACpE,oBAAoBQ,MAAMN,YAAY,GAAG,WAAW;QACpD,kBAAkBM,MAAML,QAAQ,GAAG,IAAIa,OAAOR,MAAML,QAAQ,IAAI;QAChE,uBAAuBK,MAAMJ,cAAc,GAAG,OAAO;IACvD;AACF"}
+8
View File
@@ -4,6 +4,7 @@ import { Cookie } from 'lucide-react';
import { useEffect, useState } from 'react';
import { CONSENT_CATEGORIES } from './categories.js';
import { useConsentContext } from './ConsentContext.js';
import { useIsMounted } from './useIsMounted.js';
/**
* Colours and radius come from CSS custom properties with built-in fallbacks,
* so the banner looks right with no setup, and re-skinning per client means
@@ -36,6 +37,7 @@ const bodyText = 'text-[var(--ipal-text,#404040)] dark:text-[var(--ipal-text-dar
const strongText = 'text-[var(--ipal-text-strong,#171717)] dark:text-[var(--ipal-text-strong-dark,#f5f5f5)]';
const mutedText = 'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]';
export function CookieBanner({ classNames } = {}) {
const isMounted = useIsMounted();
const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext();
const [showSettings, setShowSettings] = useState(false);
const [choices, setChoices] = useState(state);
@@ -44,6 +46,12 @@ export function CookieBanner({ classNames } = {}) {
}, [
state
]);
// Render nothing until mounted — avoids the React 19 hydration mismatch that
// projects used to work around with a setTimeout ConsentWrapper. No wrapper
// needed now.
if (!isMounted) {
return null;
}
if (decided) {
return null;
}
File diff suppressed because one or more lines are too long
+7
View File
@@ -2,6 +2,7 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { Cookie } from 'lucide-react';
import { useConsentContext } from './ConsentContext.js';
import { useIsMounted } from './useIsMounted.js';
/**
* Floating "cookie settings" button — lets visitors reopen the consent panel
* after deciding (GDPR: withdrawing consent must be as easy as giving it).
@@ -12,7 +13,13 @@ import { useConsentContext } from './ConsentContext.js';
* palette applies to both without touching either component. Pass className to
* replace the styling outright.
*/ export function CookieButton({ className } = {}) {
const isMounted = useIsMounted();
const { decided, reopen } = useConsentContext();
// Render nothing until mounted — prevents hydration mismatch (no project
// ConsentWrapper workaround needed).
if (!isMounted) {
return null;
}
if (!decided) {
return null;
}
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/consent/CookieButton.tsx"],"sourcesContent":["'use client'\nimport { Cookie } from 'lucide-react'\n\nimport { useConsentContext } from './ConsentContext.js'\n\n/**\n * Floating \"cookie settings\" button — lets visitors reopen the consent panel\n * after deciding (GDPR: withdrawing consent must be as easy as giving it).\n * Hidden while the banner is showing.\n *\n * Colours follow the same CSS custom properties as CookieBanner\n * (--ipal-surface, --ipal-border, --ipal-hover, --ipal-text), so a client's\n * palette applies to both without touching either component. Pass className to\n * replace the styling outright.\n */\nexport function CookieButton({ className }: { className?: string } = {}) {\n const { decided, reopen } = useConsentContext()\n\n if (!decided) {return null}\n\n const cls =\n className ??\n 'fixed bottom-4 left-4 z-40 flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-colors ' +\n 'bg-[var(--ipal-surface,#fff)] border-[var(--ipal-border,#e5e5e5)] hover:bg-[var(--ipal-hover,#f5f5f5)] ' +\n 'dark:bg-[var(--ipal-surface-dark,#171717)] dark:border-[var(--ipal-border-dark,#262626)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]'\n\n return (\n <button aria-label=\"Cookie settings\" className={cls} data-ipal=\"cookie-button\" onClick={reopen}>\n <Cookie\n aria-hidden=\"true\"\n className=\"h-5 w-5 text-[var(--ipal-text,#525252)] dark:text-[var(--ipal-text-dark,#d4d4d4)]\"\n />\n </button>\n )\n}\n"],"names":["Cookie","useConsentContext","CookieButton","className","decided","reopen","cls","button","aria-label","data-ipal","onClick","aria-hidden"],"mappings":"AAAA;;AACA,SAASA,MAAM,QAAQ,eAAc;AAErC,SAASC,iBAAiB,QAAQ,sBAAqB;AAEvD;;;;;;;;;CASC,GACD,OAAO,SAASC,aAAa,EAAEC,SAAS,EAA0B,GAAG,CAAC,CAAC;IACrE,MAAM,EAAEC,OAAO,EAAEC,MAAM,EAAE,GAAGJ;IAE5B,IAAI,CAACG,SAAS;QAAC,OAAO;IAAI;IAE1B,MAAME,MACJH,aACA,2HACE,4GACA;IAEJ,qBACE,KAACI;QAAOC,cAAW;QAAkBL,WAAWG;QAAKG,aAAU;QAAgBC,SAASL;kBACtF,cAAA,KAACL;YACCW,eAAY;YACZR,WAAU;;;AAIlB"}
{"version":3,"sources":["../../../src/modules/consent/CookieButton.tsx"],"sourcesContent":["'use client'\nimport { Cookie } from 'lucide-react'\n\nimport { useConsentContext } from './ConsentContext.js'\nimport { useIsMounted } from './useIsMounted.js'\n\n/**\n * Floating \"cookie settings\" button — lets visitors reopen the consent panel\n * after deciding (GDPR: withdrawing consent must be as easy as giving it).\n * Hidden while the banner is showing.\n *\n * Colours follow the same CSS custom properties as CookieBanner\n * (--ipal-surface, --ipal-border, --ipal-hover, --ipal-text), so a client's\n * palette applies to both without touching either component. Pass className to\n * replace the styling outright.\n */\nexport function CookieButton({ className }: { className?: string } = {}) {\n const isMounted = useIsMounted()\n const { decided, reopen } = useConsentContext()\n\n // Render nothing until mounted — prevents hydration mismatch (no project\n // ConsentWrapper workaround needed).\n if (!isMounted) {return null}\n if (!decided) {return null}\n\n const cls =\n className ??\n 'fixed bottom-4 left-4 z-40 flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-colors ' +\n 'bg-[var(--ipal-surface,#fff)] border-[var(--ipal-border,#e5e5e5)] hover:bg-[var(--ipal-hover,#f5f5f5)] ' +\n 'dark:bg-[var(--ipal-surface-dark,#171717)] dark:border-[var(--ipal-border-dark,#262626)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]'\n\n return (\n <button aria-label=\"Cookie settings\" className={cls} data-ipal=\"cookie-button\" onClick={reopen}>\n <Cookie\n aria-hidden=\"true\"\n className=\"h-5 w-5 text-[var(--ipal-text,#525252)] dark:text-[var(--ipal-text-dark,#d4d4d4)]\"\n />\n </button>\n )\n}\n"],"names":["Cookie","useConsentContext","useIsMounted","CookieButton","className","isMounted","decided","reopen","cls","button","aria-label","data-ipal","onClick","aria-hidden"],"mappings":"AAAA;;AACA,SAASA,MAAM,QAAQ,eAAc;AAErC,SAASC,iBAAiB,QAAQ,sBAAqB;AACvD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD;;;;;;;;;CASC,GACD,OAAO,SAASC,aAAa,EAAEC,SAAS,EAA0B,GAAG,CAAC,CAAC;IACrE,MAAMC,YAAYH;IAClB,MAAM,EAAEI,OAAO,EAAEC,MAAM,EAAE,GAAGN;IAE5B,yEAAyE;IACzE,qCAAqC;IACrC,IAAI,CAACI,WAAW;QAAC,OAAO;IAAI;IAC5B,IAAI,CAACC,SAAS;QAAC,OAAO;IAAI;IAE1B,MAAME,MACJJ,aACA,2HACE,4GACA;IAEJ,qBACE,KAACK;QAAOC,cAAW;QAAkBN,WAAWI;QAAKG,aAAU;QAAgBC,SAASL;kBACtF,cAAA,KAACP;YACCa,eAAY;YACZT,WAAU;;;AAIlB"}
+1
View File
@@ -4,3 +4,4 @@ export { getConsentTexts } from './getConsentTexts.js';
export { setDefaultConsent, updateConsent } from './googleConsent.js';
export { CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, parseConsent, serializeConsent, } from './storage.js';
export type { ConsentTexts } from './texts.js';
export { useIsMounted } from './useIsMounted.js';
+1
View File
@@ -5,5 +5,6 @@ export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, DEFAULT_CONSENT, REJECT_ALL_CON
export { getConsentTexts } from './getConsentTexts.js';
export { setDefaultConsent, updateConsent } from './googleConsent.js';
export { CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, parseConsent, serializeConsent } from './storage.js';
export { useIsMounted } from './useIsMounted.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/consent/index.ts"],"sourcesContent":["// Server-safe exports (logic, types, helper). Client components (banner,\n// provider, hook) are exported separately via ./client to keep the RSC/client\n// boundary clean.\nexport {\n ACCEPT_ALL_CONSENT,\n CONSENT_CATEGORIES,\n DEFAULT_CONSENT,\n REJECT_ALL_CONSENT,\n} from './categories.js'\nexport type { ConsentCategory, ConsentState } from './categories.js'\nexport { getConsentTexts } from './getConsentTexts.js'\nexport { setDefaultConsent, updateConsent } from './googleConsent.js'\nexport {\n CONSENT_COOKIE,\n CONSENT_MAX_AGE,\n CONSENT_VERSION,\n parseConsent,\n serializeConsent,\n} from './storage.js'\nexport type { ConsentTexts } from './texts.js'\n"],"names":["ACCEPT_ALL_CONSENT","CONSENT_CATEGORIES","DEFAULT_CONSENT","REJECT_ALL_CONSENT","getConsentTexts","setDefaultConsent","updateConsent","CONSENT_COOKIE","CONSENT_MAX_AGE","CONSENT_VERSION","parseConsent","serializeConsent"],"mappings":"AAAA,yEAAyE;AACzE,8EAA8E;AAC9E,kBAAkB;AAClB,SACEA,kBAAkB,EAClBC,kBAAkB,EAClBC,eAAe,EACfC,kBAAkB,QACb,kBAAiB;AAExB,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,iBAAiB,EAAEC,aAAa,QAAQ,qBAAoB;AACrE,SACEC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,YAAY,EACZC,gBAAgB,QACX,eAAc"}
{"version":3,"sources":["../../../src/modules/consent/index.ts"],"sourcesContent":["// Server-safe exports (logic, types, helper). Client components (banner,\n// provider, hook) are exported separately via ./client to keep the RSC/client\n// boundary clean.\nexport {\n ACCEPT_ALL_CONSENT,\n CONSENT_CATEGORIES,\n DEFAULT_CONSENT,\n REJECT_ALL_CONSENT,\n} from './categories.js'\nexport type { ConsentCategory, ConsentState } from './categories.js'\nexport { getConsentTexts } from './getConsentTexts.js'\nexport { setDefaultConsent, updateConsent } from './googleConsent.js'\nexport {\n CONSENT_COOKIE,\n CONSENT_MAX_AGE,\n CONSENT_VERSION,\n parseConsent,\n serializeConsent,\n} from './storage.js'\nexport type { ConsentTexts } from './texts.js'\nexport { useIsMounted } from './useIsMounted.js'\n"],"names":["ACCEPT_ALL_CONSENT","CONSENT_CATEGORIES","DEFAULT_CONSENT","REJECT_ALL_CONSENT","getConsentTexts","setDefaultConsent","updateConsent","CONSENT_COOKIE","CONSENT_MAX_AGE","CONSENT_VERSION","parseConsent","serializeConsent","useIsMounted"],"mappings":"AAAA,yEAAyE;AACzE,8EAA8E;AAC9E,kBAAkB;AAClB,SACEA,kBAAkB,EAClBC,kBAAkB,EAClBC,eAAe,EACfC,kBAAkB,QACb,kBAAiB;AAExB,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,iBAAiB,EAAEC,aAAa,QAAQ,qBAAoB;AACrE,SACEC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,YAAY,EACZC,gBAAgB,QACX,eAAc;AAErB,SAASC,YAAY,QAAQ,oBAAmB"}
+8
View File
@@ -0,0 +1,8 @@
/**
* Returns true only after the component has mounted on the client. Used to gate
* consent UI (CookieBanner, CookieButton) so it renders nothing during SSR /
* first paint — preventing the React 19 / Next hydration mismatch that projects
* were working around with their own setTimeout-based ConsentWrapper. Built into
* the components now, so no project wrapper is needed.
*/
export declare function useIsMounted(): boolean;
+17
View File
@@ -0,0 +1,17 @@
'use client';
import { useEffect, useState } from 'react';
/**
* Returns true only after the component has mounted on the client. Used to gate
* consent UI (CookieBanner, CookieButton) so it renders nothing during SSR /
* first paint — preventing the React 19 / Next hydration mismatch that projects
* were working around with their own setTimeout-based ConsentWrapper. Built into
* the components now, so no project wrapper is needed.
*/ export function useIsMounted() {
const [mounted, setMounted] = useState(false);
useEffect(()=>{
setMounted(true);
}, []);
return mounted;
}
//# sourceMappingURL=useIsMounted.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/consent/useIsMounted.ts"],"sourcesContent":["'use client'\nimport { useEffect, useState } from 'react'\n\n/**\n * Returns true only after the component has mounted on the client. Used to gate\n * consent UI (CookieBanner, CookieButton) so it renders nothing during SSR /\n * first paint — preventing the React 19 / Next hydration mismatch that projects\n * were working around with their own setTimeout-based ConsentWrapper. Built into\n * the components now, so no project wrapper is needed.\n */\nexport function useIsMounted(): boolean {\n const [mounted, setMounted] = useState(false)\n useEffect(() => {\n setMounted(true)\n }, [])\n return mounted\n}\n"],"names":["useEffect","useState","useIsMounted","mounted","setMounted"],"mappings":"AAAA;AACA,SAASA,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAE3C;;;;;;CAMC,GACD,OAAO,SAASC;IACd,MAAM,CAACC,SAASC,WAAW,GAAGH,SAAS;IACvCD,UAAU;QACRI,WAAW;IACb,GAAG,EAAE;IACL,OAAOD;AACT"}
+6
View File
@@ -4,5 +4,11 @@ export type { RateLimitArgs } from './rateLimit.js';
export { submitForm } from './submitForm.js';
export type { SubmitFormArgs, SubmitFormResult } from './submitForm.js';
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js';
export { useContactForm } from './useContactForm.js';
export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js';
export { useForm } from './useForm.js';
export type { FormErrors, FormSubmitAction, Validator } from './useForm.js';
export { validateSubmission } from './validateSubmission.js';
export type { FormValidationResult } from './validateSubmission.js';
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from './validators.js';
export type { Rule } from './validators.js';
+5
View File
@@ -3,6 +3,11 @@
export { buildFormsPlugin } from './formsPluginConfig.js';
export { checkRateLimit } from './rateLimit.js';
export { submitForm } from './submitForm.js';
export { useContactForm } from './useContactForm.js';
// Generic form engine (any field set) + the standard contact-form preset.
export { useForm } from './useForm.js';
export { validateSubmission } from './validateSubmission.js';
// Composable validation rules (pure — safe on server or client).
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from './validators.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","validateSubmission"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,kBAAkB,QAAQ,0BAAyB"}
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { useContactForm } from './useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'\n// Generic form engine (any field set) + the standard contact-form preset.\nexport { useForm } from './useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './useForm.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n// Composable validation rules (pure — safe on server or client).\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from './validators.js'\nexport type { Rule } from './validators.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","useContactForm","useForm","validateSubmission","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,0EAA0E;AAC1E,SAASC,OAAO,QAAQ,eAAc;AAEtC,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,iEAAiE;AACjE,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,kBAAiB"}
+60
View File
@@ -0,0 +1,60 @@
import { type FormSubmitAction } from './useForm.js';
/**
* Field values of the STANDARD contact form. This is a preset shape — projects
* that need a different field set (or dynamic builder fields) should use
* `useForm` directly instead, where the shape is fully open.
*/
export type ContactFormValues = {
consent: boolean;
email: string;
message: string;
name: string;
phone: string;
topic: string;
};
export type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>;
export type SubmitAction = FormSubmitAction<ContactFormValues>;
type UseContactFormOptions = {
/** Generic error message shown when the action fails/throws. */
errorFallback?: string;
initialTopic?: string;
/** Override the per-field error message (shown via `errors.<field>`). */
messages?: Partial<Record<keyof ContactFormValues, string>>;
/** Minimum message length. Default 10. */
minMessageLength?: number;
/** Whether consent is required (project passes true when consentText shown). */
requireConsent?: boolean;
/** Whether a topic must be chosen (project passes this when topics exist). */
requireTopic?: boolean;
/** Require a Turnstile token before submit (when the widget is shown). */
requireTurnstile?: boolean;
submitAction: SubmitAction;
};
/**
* Zero-config preset over `useForm` for the everyday contact form: standard
* fields (name/email/phone/topic/message/consent) and standard rules, wired
* for you. Markup and styling stay 100% in the project — this only removes the
* duplicated logic.
*
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
*
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
*/
export declare function useContactForm(options: UseContactFormOptions): {
values: ContactFormValues;
errors: Partial<Record<keyof ContactFormValues, string>>;
isSubmitting: boolean;
isSuccess: boolean;
errorMessage: string | null;
turnstileToken: string | null;
setField: <K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => void;
setValues: import("react").Dispatch<import("react").SetStateAction<ContactFormValues>>;
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof ContactFormValues, string>>>>;
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
handleSubmit: (e?: {
preventDefault?: (() => void) | undefined;
} | undefined) => Promise<void>;
reset: () => void;
};
export {};
+61
View File
@@ -0,0 +1,61 @@
'use client';
import { useMemo } from 'react';
import { useForm } from './useForm.js';
import { buildValidator, checked, email, minLength, required } from './validators.js';
/**
* Zero-config preset over `useForm` for the everyday contact form: standard
* fields (name/email/phone/topic/message/consent) and standard rules, wired
* for you. Markup and styling stay 100% in the project — this only removes the
* duplicated logic.
*
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
*
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
*/ export function useContactForm(options) {
const { errorFallback, initialTopic = '', messages, minMessageLength = 10, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction } = options;
const validate = useMemo(()=>buildValidator({
name: [
required(messages?.name)
],
email: [
required(messages?.email),
email(messages?.email)
],
...requireTopic ? {
topic: [
required(messages?.topic)
]
} : {},
message: [
required(messages?.message),
minLength(minMessageLength, messages?.message)
],
...requireConsent ? {
consent: [
checked(messages?.consent)
]
} : {}
}), [
requireTopic,
requireConsent,
minMessageLength,
messages
]);
return useForm({
errorFallback,
initialValues: {
name: '',
consent: false,
email: '',
message: '',
phone: '',
topic: initialTopic
},
requireTurnstile,
submitAction,
validate
});
}
//# sourceMappingURL=useContactForm.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/forms/useContactForm.ts"],"sourcesContent":["'use client'\n\nimport { useMemo } from 'react'\n\nimport { type FormSubmitAction, useForm } from './useForm.js'\nimport { buildValidator, checked, email, minLength, required } from './validators.js'\n\n/**\n * Field values of the STANDARD contact form. This is a preset shape — projects\n * that need a different field set (or dynamic builder fields) should use\n * `useForm` directly instead, where the shape is fully open.\n */\nexport type ContactFormValues = {\n consent: boolean\n email: string\n message: string\n name: string\n phone: string\n topic: string\n}\n\nexport type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>\nexport type SubmitAction = FormSubmitAction<ContactFormValues>\n\ntype UseContactFormOptions = {\n /** Generic error message shown when the action fails/throws. */\n errorFallback?: string\n initialTopic?: string\n /** Override the per-field error message (shown via `errors.<field>`). */\n messages?: Partial<Record<keyof ContactFormValues, string>>\n /** Minimum message length. Default 10. */\n minMessageLength?: number\n /** Whether consent is required (project passes true when consentText shown). */\n requireConsent?: boolean\n /** Whether a topic must be chosen (project passes this when topics exist). */\n requireTopic?: boolean\n /** Require a Turnstile token before submit (when the widget is shown). */\n requireTurnstile?: boolean\n submitAction: SubmitAction\n}\n\n/**\n * Zero-config preset over `useForm` for the everyday contact form: standard\n * fields (name/email/phone/topic/message/consent) and standard rules, wired\n * for you. Markup and styling stay 100% in the project — this only removes the\n * duplicated logic.\n *\n * const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),\n * requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })\n *\n * Need custom or dynamic fields? Drop the preset and call `useForm` + validators.\n */\nexport function useContactForm(options: UseContactFormOptions) {\n const {\n errorFallback,\n initialTopic = '',\n messages,\n minMessageLength = 10,\n requireConsent = false,\n requireTopic = false,\n requireTurnstile = false,\n submitAction,\n } = options\n\n const validate = useMemo(\n () =>\n buildValidator<ContactFormValues>({\n name: [required(messages?.name)],\n email: [required(messages?.email), email(messages?.email)],\n ...(requireTopic ? { topic: [required(messages?.topic)] } : {}),\n message: [required(messages?.message), minLength(minMessageLength, messages?.message)],\n ...(requireConsent ? { consent: [checked(messages?.consent)] } : {}),\n }),\n [requireTopic, requireConsent, minMessageLength, messages],\n )\n\n return useForm<ContactFormValues>({\n errorFallback,\n initialValues: {\n name: '',\n consent: false,\n email: '',\n message: '',\n phone: '',\n topic: initialTopic,\n },\n requireTurnstile,\n submitAction,\n validate,\n })\n}\n"],"names":["useMemo","useForm","buildValidator","checked","email","minLength","required","useContactForm","options","errorFallback","initialTopic","messages","minMessageLength","requireConsent","requireTopic","requireTurnstile","submitAction","validate","name","topic","message","consent","initialValues","phone"],"mappings":"AAAA;AAEA,SAASA,OAAO,QAAQ,QAAO;AAE/B,SAAgCC,OAAO,QAAQ,eAAc;AAC7D,SAASC,cAAc,EAAEC,OAAO,EAAEC,KAAK,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,kBAAiB;AAoCrF;;;;;;;;;;CAUC,GACD,OAAO,SAASC,eAAeC,OAA8B;IAC3D,MAAM,EACJC,aAAa,EACbC,eAAe,EAAE,EACjBC,QAAQ,EACRC,mBAAmB,EAAE,EACrBC,iBAAiB,KAAK,EACtBC,eAAe,KAAK,EACpBC,mBAAmB,KAAK,EACxBC,YAAY,EACb,GAAGR;IAEJ,MAAMS,WAAWjB,QACf,IACEE,eAAkC;YAChCgB,MAAM;gBAACZ,SAASK,UAAUO;aAAM;YAChCd,OAAO;gBAACE,SAASK,UAAUP;gBAAQA,MAAMO,UAAUP;aAAO;YAC1D,GAAIU,eAAe;gBAAEK,OAAO;oBAACb,SAASK,UAAUQ;iBAAO;YAAC,IAAI,CAAC,CAAC;YAC9DC,SAAS;gBAACd,SAASK,UAAUS;gBAAUf,UAAUO,kBAAkBD,UAAUS;aAAS;YACtF,GAAIP,iBAAiB;gBAAEQ,SAAS;oBAAClB,QAAQQ,UAAUU;iBAAS;YAAC,IAAI,CAAC,CAAC;QACrE,IACF;QAACP;QAAcD;QAAgBD;QAAkBD;KAAS;IAG5D,OAAOV,QAA2B;QAChCQ;QACAa,eAAe;YACbJ,MAAM;YACNG,SAAS;YACTjB,OAAO;YACPgB,SAAS;YACTG,OAAO;YACPJ,OAAOT;QACT;QACAK;QACAC;QACAC;IACF;AACF"}
+70
View File
@@ -0,0 +1,70 @@
/**
* Error map: a field key → its error message. A field is "in error" iff it has
* a key here, so `errors.email` is both the truthy flag (for a red border) AND
* the message (to display). Empty object = valid.
*/
export type FormErrors<T> = Partial<Record<keyof T, string>>;
/**
* The project's server action that calls submitForm (server-only, holds the
* Turnstile secret). This hook is a client hook, so it can't call submitForm
* directly — the project injects its action. The result only needs `success`
* plus an optional `message`; richer shapes (SubmitFormResult) satisfy it.
*/
export type FormSubmitAction<T> = (values: T, turnstileToken?: string) => Promise<{
success: boolean;
message?: string;
}>;
/** Turns the current values into an error map. Empty map = valid. */
export type Validator<T> = (values: T) => FormErrors<T>;
type UseFormOptions<T extends Record<string, unknown>> = {
/** Defines the field set AND the reset state. Any shape you like. */
initialValues: T;
submitAction: FormSubmitAction<T>;
/** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */
validate?: Validator<T>;
/** Require a Turnstile token before submit (when the widget is shown). */
requireTurnstile?: boolean;
/** Generic error message shown when the action fails/throws with no message. */
errorFallback?: string;
/** Clear a field's error as soon as the user edits it. Default true. */
clearErrorOnChange?: boolean;
};
/**
* Fully generic form engine: state, validation, Turnstile token, submit,
* success/error — WITHOUT any markup. The project owns 100% of the look AND
* the field set: there is no baked-in shape here. Replaces the identical
* ~150 lines of form plumbing copied into every project.
*
* The field set comes from `initialValues`; the rules come from `validate`
* (so dynamic/builder-driven forms just build both at runtime). For the
* everyday contact form use the `useContactForm` preset instead — it wires
* the standard fields and rules for you.
*
* const f = useForm({
* initialValues: { email: '', message: '' },
* submitAction, // your server action
* validate: buildValidator({ email: [required(), email()], message: [required()] }),
* requireTurnstile: Boolean(siteKey),
* })
* <input value={f.values.email}
* onChange={(e) => f.setField('email', e.target.value)}
* className={f.errors.email ? 'border-red-500' : '…'} />
* <form onSubmit={f.handleSubmit}>…</form>
*/
export declare function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>): {
values: T;
errors: Partial<Record<keyof T, string>>;
isSubmitting: boolean;
isSuccess: boolean;
errorMessage: string | null;
turnstileToken: string | null;
setField: <K extends keyof T>(key: K, value: T[K]) => void;
setValues: import("react").Dispatch<import("react").SetStateAction<T>>;
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof T, string>>>>;
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
handleSubmit: (e?: {
preventDefault?: () => void;
}) => Promise<void>;
reset: () => void;
};
export {};
+122
View File
@@ -0,0 +1,122 @@
'use client';
import { useState, useCallback, useRef, useMemo } from 'react';
/**
* Fully generic form engine: state, validation, Turnstile token, submit,
* success/error — WITHOUT any markup. The project owns 100% of the look AND
* the field set: there is no baked-in shape here. Replaces the identical
* ~150 lines of form plumbing copied into every project.
*
* The field set comes from `initialValues`; the rules come from `validate`
* (so dynamic/builder-driven forms just build both at runtime). For the
* everyday contact form use the `useContactForm` preset instead — it wires
* the standard fields and rules for you.
*
* const f = useForm({
* initialValues: { email: '', message: '' },
* submitAction, // your server action
* validate: buildValidator({ email: [required(), email()], message: [required()] }),
* requireTurnstile: Boolean(siteKey),
* })
* <input value={f.values.email}
* onChange={(e) => f.setField('email', e.target.value)}
* className={f.errors.email ? 'border-red-500' : '…'} />
* <form onSubmit={f.handleSubmit}>…</form>
*/ export function useForm(options) {
const { initialValues, submitAction, validate, requireTurnstile = false, errorFallback = 'Something went wrong. Please try again.', clearErrorOnChange = true } = options;
// Freeze the initial snapshot so `reset` is stable even though callers pass a
// fresh object literal every render.
const initialRef = useRef(initialValues);
const [values, setValues] = useState(initialRef.current);
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [errorMessage, setErrorMessage] = useState(null);
const [turnstileToken, setTurnstileToken] = useState(null);
const setField = useCallback((key, value)=>{
setValues((prev)=>({
...prev,
[key]: value
}));
if (clearErrorOnChange) {
setErrors((prev)=>{
if (!prev[key]) return prev;
const next = {
...prev
};
delete next[key];
return next;
});
}
}, [
clearErrorOnChange
]);
// Validate against the LATEST values via a ref, so handleSubmit stays stable
// and never reads a stale snapshot.
const valuesRef = useRef(values);
valuesRef.current = values;
const validateRef = useRef(validate);
validateRef.current = validate;
const handleSubmit = useCallback(async (e)=>{
e?.preventDefault?.();
setErrorMessage(null);
const errs = validateRef.current ? validateRef.current(valuesRef.current) : {};
setErrors(errs);
if (Object.keys(errs).length > 0) return;
if (requireTurnstile && !turnstileToken) {
setErrorMessage(errorFallback);
return;
}
setIsSubmitting(true);
try {
const result = await submitAction(valuesRef.current, turnstileToken ?? undefined);
if (result.success) {
setIsSuccess(true);
setTurnstileToken(null);
} else {
setErrorMessage(result.message || errorFallback);
}
} catch (err) {
setErrorMessage(err instanceof Error ? err.message : errorFallback);
} finally{
setIsSubmitting(false);
}
}, [
requireTurnstile,
turnstileToken,
submitAction,
errorFallback
]);
const reset = useCallback(()=>{
setValues(initialRef.current);
setErrors({});
setIsSuccess(false);
setErrorMessage(null);
setTurnstileToken(null);
}, []);
return useMemo(()=>({
values,
errors,
isSubmitting,
isSuccess,
errorMessage,
turnstileToken,
setField,
setValues,
setErrors,
setTurnstileToken,
handleSubmit,
reset
}), [
values,
errors,
isSubmitting,
isSuccess,
errorMessage,
turnstileToken,
setField,
handleSubmit,
reset
]);
}
//# sourceMappingURL=useForm.js.map
File diff suppressed because one or more lines are too long
+43
View File
@@ -0,0 +1,43 @@
import type { Validator } from './useForm.js';
/**
* Composable validation rules + a builder that turns a per-field schema into a
* `Validator<T>`. These are the bits that actually repeat across projects
* (required / email / min-length / checkbox-must-be-true); the field SET and
* the MARKUP stay in the project.
*
* Pure functions, no 'use client' — usable both in the client `useForm` hook
* and server-side (e.g. re-validating inside a server action).
*
* const validate = buildValidator<MyValues>({
* email: [required(), email()],
* message: [required(), minLength(10)],
* consent: [checked()],
* })
*
* Dynamic / builder-driven forms build the schema at runtime:
*
* const schema = Object.fromEntries(
* fields.map((f) => [f.name, f.required ? [required()] : []]),
* )
* const validate = buildValidator(schema)
*/
/** A rule returns `true` when the value is OK, or an error message string. */
export type Rule = (value: unknown, values: Record<string, unknown>) => true | string;
/** Standalone e-mail check, handy outside the rule system too. */
export declare const isEmail: (v: unknown) => boolean;
/** Non-empty string, non-null, and (for checkboxes) not `false`. */
export declare const required: (msg?: string) => Rule;
export declare const email: (msg?: string) => Rule;
export declare const minLength: (n: number, msg?: string) => Rule;
export declare const maxLength: (n: number, msg?: string) => Rule;
/** Checkbox must be ticked (true). */
export declare const checked: (msg?: string) => Rule;
/** Value must match a regex (ignored when empty — pair with `required` to force). */
export declare const pattern: (re: RegExp, msg?: string) => Rule;
/** Escape hatch: any predicate → rule. */
export declare const custom: (test: (value: unknown, values: Record<string, unknown>) => boolean, msg: string) => Rule;
/**
* Compose a `Validator<T>` from per-field rule lists. First failing rule for a
* field wins. Fields with no rules (or an empty list) are skipped.
*/
export declare function buildValidator<T extends Record<string, unknown>>(schema: Partial<Record<keyof T, Rule[]>>): Validator<T>;
+37
View File
@@ -0,0 +1,37 @@
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
/** Standalone e-mail check, handy outside the rule system too. */ export const isEmail = (v)=>typeof v === 'string' && EMAIL_RE.test(v.trim());
/** Non-empty string, non-null, and (for checkboxes) not `false`. */ export const required = (msg = 'required')=>(v)=>{
if (v == null) return msg;
if (typeof v === 'string' && !v.trim()) return msg;
if (v === false) return msg;
return true;
};
export const email = (msg = 'invalid email')=>(v)=>isEmail(v) ? true : msg;
export const minLength = (n, msg)=>(v)=>typeof v === 'string' && v.trim().length >= n ? true : msg ?? `min ${n} chars`;
export const maxLength = (n, msg)=>(v)=>typeof v === 'string' && v.trim().length <= n ? true : msg ?? `max ${n} chars`;
/** Checkbox must be ticked (true). */ export const checked = (msg = 'required')=>(v)=>v === true ? true : msg;
/** Value must match a regex (ignored when empty — pair with `required` to force). */ export const pattern = (re, msg = 'invalid format')=>(v)=>typeof v !== 'string' || v.trim() === '' || re.test(v.trim()) ? true : msg;
/** Escape hatch: any predicate → rule. */ export const custom = (test, msg)=>(v, values)=>test(v, values) ? true : msg;
/**
* Compose a `Validator<T>` from per-field rule lists. First failing rule for a
* field wins. Fields with no rules (or an empty list) are skipped.
*/ export function buildValidator(schema) {
return (values)=>{
const errs = {};
const all = values;
for(const key in schema){
const rules = schema[key];
if (!rules || rules.length === 0) continue;
for (const rule of rules){
const res = rule(all[key], all);
if (res !== true) {
errs[key] = res;
break;
}
}
}
return errs;
};
}
//# sourceMappingURL=validators.js.map
File diff suppressed because one or more lines are too long
+22
View File
@@ -0,0 +1,22 @@
/** Map of locale code → absolute-or-relative URL for the current page. */
export type AlternateLinks = Record<string, string>;
/**
* Holds the current page's per-locale URLs so a LanguageSwitcher links to the
* CORRECT localized slug instead of naively swapping the locale prefix
* (/pl/uslugi → /en/uslugi, which 404s when the English slug is /en/services).
*
* Wrap the app once; each page reports its own alternates via
* <AlternateLinksUpdater> (or useSetAlternateLinks). The switcher reads them
* with useAlternateLinks().
*
* // layout.tsx
* import { AlternateLinksProvider } from '@intecion/ipal-kit/client'
* <AlternateLinksProvider>{children}</AlternateLinksProvider>
*/
export declare function AlternateLinksProvider({ children }: {
children: React.ReactNode;
}): import("react/jsx-runtime").JSX.Element;
/** Read the current page's per-locale URLs (for a language switcher). */
export declare function useAlternateLinks(): AlternateLinks;
/** Setter for the alternates (used by AlternateLinksUpdater). */
export declare function useSetAlternateLinks(): (links: AlternateLinks) => void;
+37
View File
@@ -0,0 +1,37 @@
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, use, useCallback, useState } from 'react';
const AlternateLinksContext = /*#__PURE__*/ createContext(null);
/**
* Holds the current page's per-locale URLs so a LanguageSwitcher links to the
* CORRECT localized slug instead of naively swapping the locale prefix
* (/pl/uslugi → /en/uslugi, which 404s when the English slug is /en/services).
*
* Wrap the app once; each page reports its own alternates via
* <AlternateLinksUpdater> (or useSetAlternateLinks). The switcher reads them
* with useAlternateLinks().
*
* // layout.tsx
* import { AlternateLinksProvider } from '@intecion/ipal-kit/client'
* <AlternateLinksProvider>{children}</AlternateLinksProvider>
*/ export function AlternateLinksProvider({ children }) {
const [links, setLinksState] = useState({});
const setLinks = useCallback((next)=>setLinksState(next), []);
return /*#__PURE__*/ _jsx(AlternateLinksContext, {
value: {
links,
setLinks
},
children: children
});
}
/** Read the current page's per-locale URLs (for a language switcher). */ export function useAlternateLinks() {
const ctx = use(AlternateLinksContext);
return ctx?.links ?? {};
}
/** Setter for the alternates (used by AlternateLinksUpdater). */ export function useSetAlternateLinks() {
const ctx = use(AlternateLinksContext);
return ctx?.setLinks ?? (()=>{});
}
//# sourceMappingURL=AlternateLinksContext.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/i18n/AlternateLinksContext.tsx"],"sourcesContent":["'use client'\n\nimport { createContext, use, useCallback, useState } from 'react'\n\n/** Map of locale code → absolute-or-relative URL for the current page. */\nexport type AlternateLinks = Record<string, string>\n\ntype AlternateLinksContextValue = {\n links: AlternateLinks\n setLinks: (links: AlternateLinks) => void\n}\n\nconst AlternateLinksContext = createContext<AlternateLinksContextValue | null>(null)\n\n/**\n * Holds the current page's per-locale URLs so a LanguageSwitcher links to the\n * CORRECT localized slug instead of naively swapping the locale prefix\n * (/pl/uslugi → /en/uslugi, which 404s when the English slug is /en/services).\n *\n * Wrap the app once; each page reports its own alternates via\n * <AlternateLinksUpdater> (or useSetAlternateLinks). The switcher reads them\n * with useAlternateLinks().\n *\n * // layout.tsx\n * import { AlternateLinksProvider } from '@intecion/ipal-kit/client'\n * <AlternateLinksProvider>{children}</AlternateLinksProvider>\n */\nexport function AlternateLinksProvider({ children }: { children: React.ReactNode }) {\n const [links, setLinksState] = useState<AlternateLinks>({})\n const setLinks = useCallback((next: AlternateLinks) => setLinksState(next), [])\n return (\n <AlternateLinksContext value={{ links, setLinks }}>\n {children}\n </AlternateLinksContext>\n )\n}\n\n/** Read the current page's per-locale URLs (for a language switcher). */\nexport function useAlternateLinks(): AlternateLinks {\n const ctx = use(AlternateLinksContext)\n return ctx?.links ?? {}\n}\n\n/** Setter for the alternates (used by AlternateLinksUpdater). */\nexport function useSetAlternateLinks(): (links: AlternateLinks) => void {\n const ctx = use(AlternateLinksContext)\n return ctx?.setLinks ?? (() => {})\n}\n"],"names":["createContext","use","useCallback","useState","AlternateLinksContext","AlternateLinksProvider","children","links","setLinksState","setLinks","next","value","useAlternateLinks","ctx","useSetAlternateLinks"],"mappings":"AAAA;;AAEA,SAASA,aAAa,EAAEC,GAAG,EAAEC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAUjE,MAAMC,sCAAwBJ,cAAiD;AAE/E;;;;;;;;;;;;CAYC,GACD,OAAO,SAASK,uBAAuB,EAAEC,QAAQ,EAAiC;IAChF,MAAM,CAACC,OAAOC,cAAc,GAAGL,SAAyB,CAAC;IACzD,MAAMM,WAAWP,YAAY,CAACQ,OAAyBF,cAAcE,OAAO,EAAE;IAC9E,qBACE,KAACN;QAAsBO,OAAO;YAAEJ;YAAOE;QAAS;kBAC7CH;;AAGP;AAEA,uEAAuE,GACvE,OAAO,SAASM;IACd,MAAMC,MAAMZ,IAAIG;IAChB,OAAOS,KAAKN,SAAS,CAAC;AACxB;AAEA,+DAA+D,GAC/D,OAAO,SAASO;IACd,MAAMD,MAAMZ,IAAIG;IAChB,OAAOS,KAAKJ,YAAa,CAAA,KAAO,CAAA;AAClC"}
+19
View File
@@ -0,0 +1,19 @@
import { type AlternateLinks } from './AlternateLinksContext.js';
/**
* Reports the current page's per-locale URLs into AlternateLinksProvider. Render
* it on each page (a Server Component computes the links via resolveRoute /
* getLocalizedSlugs and passes them down). The switcher then links correctly.
*
* // page.tsx (RSC) — compute alternates from the resolved route
* import { AlternateLinksUpdater } from '@intecion/ipal-kit/client'
* const alternates = { pl: '/pl/uslugi/karne', en: '/en/services/criminal' }
* return <>
* <AlternateLinksUpdater links={alternates} />
* {/* page content *\/}
* </>
*
* Renders nothing; it only pushes the links into context on mount/change.
*/
export declare function AlternateLinksUpdater({ links }: {
links: AlternateLinks;
}): null;
+32
View File
@@ -0,0 +1,32 @@
'use client';
import { useEffect } from 'react';
import { useSetAlternateLinks } from './AlternateLinksContext.js';
/**
* Reports the current page's per-locale URLs into AlternateLinksProvider. Render
* it on each page (a Server Component computes the links via resolveRoute /
* getLocalizedSlugs and passes them down). The switcher then links correctly.
*
* // page.tsx (RSC) — compute alternates from the resolved route
* import { AlternateLinksUpdater } from '@intecion/ipal-kit/client'
* const alternates = { pl: '/pl/uslugi/karne', en: '/en/services/criminal' }
* return <>
* <AlternateLinksUpdater links={alternates} />
* {/* page content *\/}
* </>
*
* Renders nothing; it only pushes the links into context on mount/change.
*/ export function AlternateLinksUpdater({ links }) {
const setLinks = useSetAlternateLinks();
const key = JSON.stringify(links);
useEffect(()=>{
setLinks(links);
// key covers link changes; setLinks is stable (useCallback).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
key,
setLinks
]);
return null;
}
//# sourceMappingURL=AlternateLinksUpdater.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/i18n/AlternateLinksUpdater.tsx"],"sourcesContent":["'use client'\n\nimport { useEffect } from 'react'\n\nimport { type AlternateLinks, useSetAlternateLinks } from './AlternateLinksContext.js'\n\n/**\n * Reports the current page's per-locale URLs into AlternateLinksProvider. Render\n * it on each page (a Server Component computes the links via resolveRoute /\n * getLocalizedSlugs and passes them down). The switcher then links correctly.\n *\n * // page.tsx (RSC) — compute alternates from the resolved route\n * import { AlternateLinksUpdater } from '@intecion/ipal-kit/client'\n * const alternates = { pl: '/pl/uslugi/karne', en: '/en/services/criminal' }\n * return <>\n * <AlternateLinksUpdater links={alternates} />\n * {/* page content *\\/}\n * </>\n *\n * Renders nothing; it only pushes the links into context on mount/change.\n */\nexport function AlternateLinksUpdater({ links }: { links: AlternateLinks }) {\n const setLinks = useSetAlternateLinks()\n const key = JSON.stringify(links)\n useEffect(() => {\n setLinks(links)\n // key covers link changes; setLinks is stable (useCallback).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [key, setLinks])\n return null\n}\n"],"names":["useEffect","useSetAlternateLinks","AlternateLinksUpdater","links","setLinks","key","JSON","stringify"],"mappings":"AAAA;AAEA,SAASA,SAAS,QAAQ,QAAO;AAEjC,SAA8BC,oBAAoB,QAAQ,6BAA4B;AAEtF;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,sBAAsB,EAAEC,KAAK,EAA6B;IACxE,MAAMC,WAAWH;IACjB,MAAMI,MAAMC,KAAKC,SAAS,CAACJ;IAC3BH,UAAU;QACRI,SAASD;IACT,6DAA6D;IAC7D,uDAAuD;IACzD,GAAG;QAACE;QAAKD;KAAS;IAClB,OAAO;AACT"}
+36
View File
@@ -0,0 +1,36 @@
import type { I18nConfig } from './types.js';
export type LanguageSwitcherClassNames = {
item?: string;
itemActive?: string;
menu?: string;
root?: string;
trigger?: string;
};
type LocaleItem = {
code: string;
label: string;
};
/**
* Language switcher that links to the CORRECT localized URL per language,
* reading the current page's alternates from AlternateLinksProvider — so it
* never 404s on differing slugs (/pl/uslugi vs /en/services).
*
* Unstyled by default (classNames, like CookieBanner) — NOT a fixed
* light/dark variant, so it matches any project's design. A locale with no
* known alternate falls back to its root (/{code}).
*
* // layout/header (client), inside AlternateLinksProvider
* <LanguageSwitcher
* config={i18nConfig}
* currentLocale={locale}
* classNames={{ root: '...', trigger: '...', menu: '...', item: '...' }}
* />
*/
export declare function LanguageSwitcher({ classNames, config, currentLocale, renderLabel, }: {
classNames?: LanguageSwitcherClassNames;
config: I18nConfig;
currentLocale: string;
/** Custom label per locale (e.g. flag + code). Defaults to the config label. */
renderLabel?: (locale: LocaleItem) => React.ReactNode;
}): import("react/jsx-runtime").JSX.Element;
export {};
+65
View File
@@ -0,0 +1,65 @@
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { useAlternateLinks } from './AlternateLinksContext.js';
/**
* Language switcher that links to the CORRECT localized URL per language,
* reading the current page's alternates from AlternateLinksProvider — so it
* never 404s on differing slugs (/pl/uslugi vs /en/services).
*
* Unstyled by default (classNames, like CookieBanner) — NOT a fixed
* light/dark variant, so it matches any project's design. A locale with no
* known alternate falls back to its root (/{code}).
*
* // layout/header (client), inside AlternateLinksProvider
* <LanguageSwitcher
* config={i18nConfig}
* currentLocale={locale}
* classNames={{ root: '...', trigger: '...', menu: '...', item: '...' }}
* />
*/ export function LanguageSwitcher({ classNames, config, currentLocale, renderLabel }) {
const alternates = useAlternateLinks();
const [open, setOpen] = useState(false);
const cn = classNames ?? {};
const locales = config.locales.map((l)=>({
code: l.code,
label: l.label ?? l.code.toUpperCase()
}));
const hrefFor = (code)=>alternates[code] ?? `/${code}`;
const current = locales.find((l)=>l.code === currentLocale);
return /*#__PURE__*/ _jsxs("div", {
className: cn.root,
"data-ipal-langswitcher": true,
children: [
/*#__PURE__*/ _jsx("button", {
"aria-expanded": open,
"aria-haspopup": "true",
className: cn.trigger,
onClick: ()=>setOpen((o)=>!o),
type: "button",
children: current ? renderLabel ? renderLabel(current) : current.label : currentLocale
}),
open && /*#__PURE__*/ _jsx("ul", {
className: cn.menu,
role: "menu",
children: locales.map((loc)=>{
const active = loc.code === currentLocale;
return /*#__PURE__*/ _jsx("li", {
role: "none",
children: /*#__PURE__*/ _jsx("a", {
"aria-current": active ? 'true' : undefined,
className: `${cn.item ?? ''} ${active ? cn.itemActive ?? '' : ''}`.trim(),
href: hrefFor(loc.code),
hrefLang: loc.code,
onClick: ()=>setOpen(false),
role: "menuitem",
children: renderLabel ? renderLabel(loc) : loc.label
})
}, loc.code);
})
})
]
});
}
//# sourceMappingURL=LanguageSwitcher.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/i18n/LanguageSwitcher.tsx"],"sourcesContent":["'use client'\n\nimport { useState } from 'react'\n\nimport type { I18nConfig } from './types.js'\n\nimport { useAlternateLinks } from './AlternateLinksContext.js'\n\nexport type LanguageSwitcherClassNames = {\n item?: string\n itemActive?: string\n menu?: string\n root?: string\n trigger?: string\n}\n\ntype LocaleItem = { code: string; label: string }\n\n/**\n * Language switcher that links to the CORRECT localized URL per language,\n * reading the current page's alternates from AlternateLinksProvider — so it\n * never 404s on differing slugs (/pl/uslugi vs /en/services).\n *\n * Unstyled by default (classNames, like CookieBanner) — NOT a fixed\n * light/dark variant, so it matches any project's design. A locale with no\n * known alternate falls back to its root (/{code}).\n *\n * // layout/header (client), inside AlternateLinksProvider\n * <LanguageSwitcher\n * config={i18nConfig}\n * currentLocale={locale}\n * classNames={{ root: '...', trigger: '...', menu: '...', item: '...' }}\n * />\n */\nexport function LanguageSwitcher({\n classNames,\n config,\n currentLocale,\n renderLabel,\n}: {\n classNames?: LanguageSwitcherClassNames\n config: I18nConfig\n currentLocale: string\n /** Custom label per locale (e.g. flag + code). Defaults to the config label. */\n renderLabel?: (locale: LocaleItem) => React.ReactNode\n}) {\n const alternates = useAlternateLinks()\n const [open, setOpen] = useState(false)\n const cn = classNames ?? {}\n\n const locales: LocaleItem[] = config.locales.map((l) => ({\n code: l.code,\n label: l.label ?? l.code.toUpperCase(),\n }))\n\n const hrefFor = (code: string): string => alternates[code] ?? `/${code}`\n\n const current = locales.find((l) => l.code === currentLocale)\n\n return (\n <div className={cn.root} data-ipal-langswitcher>\n <button\n aria-expanded={open}\n aria-haspopup=\"true\"\n className={cn.trigger}\n onClick={() => setOpen((o) => !o)}\n type=\"button\"\n >\n {current ? (renderLabel ? renderLabel(current) : current.label) : currentLocale}\n </button>\n {open && (\n <ul className={cn.menu} role=\"menu\">\n {locales.map((loc) => {\n const active = loc.code === currentLocale\n return (\n <li key={loc.code} role=\"none\">\n <a\n aria-current={active ? 'true' : undefined}\n className={`${cn.item ?? ''} ${active ? (cn.itemActive ?? '') : ''}`.trim()}\n href={hrefFor(loc.code)}\n hrefLang={loc.code}\n onClick={() => setOpen(false)}\n role=\"menuitem\"\n >\n {renderLabel ? renderLabel(loc) : loc.label}\n </a>\n </li>\n )\n })}\n </ul>\n )}\n </div>\n )\n}\n"],"names":["useState","useAlternateLinks","LanguageSwitcher","classNames","config","currentLocale","renderLabel","alternates","open","setOpen","cn","locales","map","l","code","label","toUpperCase","hrefFor","current","find","div","className","root","data-ipal-langswitcher","button","aria-expanded","aria-haspopup","trigger","onClick","o","type","ul","menu","role","loc","active","li","a","aria-current","undefined","item","itemActive","trim","href","hrefLang"],"mappings":"AAAA;;AAEA,SAASA,QAAQ,QAAQ,QAAO;AAIhC,SAASC,iBAAiB,QAAQ,6BAA4B;AAY9D;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASC,iBAAiB,EAC/BC,UAAU,EACVC,MAAM,EACNC,aAAa,EACbC,WAAW,EAOZ;IACC,MAAMC,aAAaN;IACnB,MAAM,CAACO,MAAMC,QAAQ,GAAGT,SAAS;IACjC,MAAMU,KAAKP,cAAc,CAAC;IAE1B,MAAMQ,UAAwBP,OAAOO,OAAO,CAACC,GAAG,CAAC,CAACC,IAAO,CAAA;YACvDC,MAAMD,EAAEC,IAAI;YACZC,OAAOF,EAAEE,KAAK,IAAIF,EAAEC,IAAI,CAACE,WAAW;QACtC,CAAA;IAEA,MAAMC,UAAU,CAACH,OAAyBP,UAAU,CAACO,KAAK,IAAI,CAAC,CAAC,EAAEA,MAAM;IAExE,MAAMI,UAAUP,QAAQQ,IAAI,CAAC,CAACN,IAAMA,EAAEC,IAAI,KAAKT;IAE/C,qBACE,MAACe;QAAIC,WAAWX,GAAGY,IAAI;QAAEC,wBAAsB;;0BAC7C,KAACC;gBACCC,iBAAejB;gBACfkB,iBAAc;gBACdL,WAAWX,GAAGiB,OAAO;gBACrBC,SAAS,IAAMnB,QAAQ,CAACoB,IAAM,CAACA;gBAC/BC,MAAK;0BAEJZ,UAAWZ,cAAcA,YAAYY,WAAWA,QAAQH,KAAK,GAAIV;;YAEnEG,sBACC,KAACuB;gBAAGV,WAAWX,GAAGsB,IAAI;gBAAEC,MAAK;0BAC1BtB,QAAQC,GAAG,CAAC,CAACsB;oBACZ,MAAMC,SAASD,IAAIpB,IAAI,KAAKT;oBAC5B,qBACE,KAAC+B;wBAAkBH,MAAK;kCACtB,cAAA,KAACI;4BACCC,gBAAcH,SAAS,SAASI;4BAChClB,WAAW,GAAGX,GAAG8B,IAAI,IAAI,GAAG,CAAC,EAAEL,SAAUzB,GAAG+B,UAAU,IAAI,KAAM,IAAI,CAACC,IAAI;4BACzEC,MAAM1B,QAAQiB,IAAIpB,IAAI;4BACtB8B,UAAUV,IAAIpB,IAAI;4BAClBc,SAAS,IAAMnB,QAAQ;4BACvBwB,MAAK;sCAEJ3B,cAAcA,YAAY4B,OAAOA,IAAInB,KAAK;;uBATtCmB,IAAIpB,IAAI;gBAarB;;;;AAKV"}
+65
View File
@@ -0,0 +1,65 @@
import type { I18nConfig } from './types.js';
/** Re-exported so the project's proxy.ts config uses the plugin's matcher. */
export declare const DEFAULT_PROXY_MATCHER: string[];
/**
* Minimal structural types — the plugin does NOT import next/server (it's a peer
* dep not present at the plugin's own build time, which would cause TS2307).
* Next's real NextRequest / NextResponse satisfy these shapes at the call site.
*/
type ProxyRequest = {
cookies: {
get: (name: string) => {
value: string;
} | undefined;
};
headers: Headers;
nextUrl: {
clone: () => URL;
pathname: string;
search: string;
};
url: string;
};
type ProxyResponse = {
cookies: {
set: (name: string, value: string, opts?: Record<string, unknown>) => void;
};
};
/**
* Next's NextResponse constructor, injected by the project (which has next/server
* in scope). The plugin stays free of a next/server import.
*/
type NextResponseLike = {
next: (init?: {
request?: {
headers: Headers;
};
}) => ProxyResponse;
redirect: (url: string | URL) => ProxyResponse;
};
type CreateProxyOptions = {
consentCategory?: 'functional' | 'necessary';
consentCookieName?: string;
cookieName?: string;
/** Expose x-locale / x-pathname request headers to RSC. Default true. */
exposeHeaders?: boolean;
};
/**
* Ready-made Next 16 proxy (the former middleware). Wraps the plugin's locale
* logic AND the per-project boilerplate (NextResponse, x-locale / x-pathname
* headers, locale cookie, redirect). The project's proxy.ts becomes a few lines.
*
* `NextResponse` is INJECTED (the plugin never imports next/server — it's a peer
* dep absent at the plugin's build time). The project passes it:
*
* // proxy.ts (Next 16 — NOT middleware.ts)
* import { NextResponse } from 'next/server'
* import { createProxy, DEFAULT_PROXY_MATCHER } from '@intecion/ipal-kit'
* import { i18nConfig } from '@/i18n.config'
* export const proxy = createProxy(i18nConfig, { NextResponse })
* export const config = { matcher: DEFAULT_PROXY_MATCHER }
*/
export declare function createProxy(config: I18nConfig, deps: {
NextResponse: NextResponseLike;
} & CreateProxyOptions): (request: ProxyRequest) => ProxyResponse;
export {};
+49
View File
@@ -0,0 +1,49 @@
import { isValidLocale } from './helpers.js';
import { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js';
/** Re-exported so the project's proxy.ts config uses the plugin's matcher. */ export const DEFAULT_PROXY_MATCHER = DEFAULT_MIDDLEWARE_MATCHER;
/**
* Ready-made Next 16 proxy (the former middleware). Wraps the plugin's locale
* logic AND the per-project boilerplate (NextResponse, x-locale / x-pathname
* headers, locale cookie, redirect). The project's proxy.ts becomes a few lines.
*
* `NextResponse` is INJECTED (the plugin never imports next/server — it's a peer
* dep absent at the plugin's build time). The project passes it:
*
* // proxy.ts (Next 16 — NOT middleware.ts)
* import { NextResponse } from 'next/server'
* import { createProxy, DEFAULT_PROXY_MATCHER } from '@intecion/ipal-kit'
* import { i18nConfig } from '@/i18n.config'
* export const proxy = createProxy(i18nConfig, { NextResponse })
* export const config = { matcher: DEFAULT_PROXY_MATCHER }
*/ export function createProxy(config, deps) {
const { exposeHeaders = true, NextResponse, ...mwOptions } = deps;
const run = createLocaleMiddleware({
config,
...mwOptions
});
return (request)=>{
const result = run(request);
const requestHeaders = new Headers(request.headers);
if (exposeHeaders) {
const { pathname } = request.nextUrl;
const seg = pathname.split('/').filter(Boolean)[0] ?? '';
const locale = isValidLocale(seg, config) ? seg : config.defaultLocale;
requestHeaders.set('x-locale', locale);
requestHeaders.set('x-pathname', pathname);
}
const response = result.type === 'redirect' ? NextResponse.redirect(new URL(result.location, request.url)) : NextResponse.next({
request: {
headers: requestHeaders
}
});
if (result.cookie) {
response.cookies.set(result.cookie.name, result.cookie.value, {
path: '/',
sameSite: 'lax'
});
}
return response;
};
}
//# sourceMappingURL=createProxy.js.map
File diff suppressed because one or more lines are too long
+7
View File
@@ -1,10 +1,17 @@
export { AlternateLinksProvider, useAlternateLinks, useSetAlternateLinks, } from './AlternateLinksContext.js';
export type { AlternateLinks } from './AlternateLinksContext.js';
export { AlternateLinksUpdater } from './AlternateLinksUpdater.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js';
export { getLocalizedSlugs } from './getLocalizedSlugs.js';
export { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js';
export { LanguageSwitcher } from './LanguageSwitcher.js';
export type { LanguageSwitcherClassNames } from './LanguageSwitcher.js';
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js';
export type { LocaleMiddlewareResult } from './localeMiddleware.js';
export { buildLocalizationConfig } from './localizationConfig.js';
export { buildLocalizedPath, switchLocalePath } from './localizedPath.js';
export type { LocalizedSlugs } from './localizedPath.js';
export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js';
export { resolveLocalized } from './resolveLocalized.js';
export type { I18nConfig, LocaleDefinition } from './types.js';
export { validateI18nConfig } from './validation.js';
+5
View File
@@ -1,9 +1,14 @@
export { AlternateLinksProvider, useAlternateLinks, useSetAlternateLinks } from './AlternateLinksContext.js';
export { AlternateLinksUpdater } from './AlternateLinksUpdater.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js';
export { getLocalizedSlugs } from './getLocalizedSlugs.js';
export { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js';
export { LanguageSwitcher } from './LanguageSwitcher.js';
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js';
export { buildLocalizationConfig } from './localizationConfig.js';
export { buildLocalizedPath, switchLocalePath } from './localizedPath.js';
export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js';
export { resolveLocalized } from './resolveLocalized.js';
export { validateI18nConfig } from './validation.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/i18n/index.ts"],"sourcesContent":["export { getLocalizedSlugs } from './getLocalizedSlugs.js'\nexport { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'\nexport type { LocaleMiddlewareResult } from './localeMiddleware.js'\nexport { buildLocalizationConfig } from './localizationConfig.js'\nexport { buildLocalizedPath, switchLocalePath } from './localizedPath.js'\nexport type { LocalizedSlugs } from './localizedPath.js'\nexport { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'\nexport type { I18nConfig, LocaleDefinition } from './types.js'\nexport { validateI18nConfig } from './validation.js'\n"],"names":["getLocalizedSlugs","getDefaultLocale","getLocaleCodes","getLocaleDefinition","isValidLocale","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","buildLocalizationConfig","buildLocalizedPath","switchLocalePath","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","validateI18nConfig"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,aAAa,QAAQ,eAAc;AACnG,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,wBAAuB;AAE1F,SAASC,uBAAuB,QAAQ,0BAAyB;AACjE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,qBAAoB;AAEzE,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,eAAe,QAAQ,uBAAsB;AAE/F,SAASC,kBAAkB,QAAQ,kBAAiB"}
{"version":3,"sources":["../../../src/modules/i18n/index.ts"],"sourcesContent":["export {\n AlternateLinksProvider,\n useAlternateLinks,\n useSetAlternateLinks,\n} from './AlternateLinksContext.js'\nexport type { AlternateLinks } from './AlternateLinksContext.js'\nexport { AlternateLinksUpdater } from './AlternateLinksUpdater.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js'\nexport { getLocalizedSlugs } from './getLocalizedSlugs.js'\nexport { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js'\nexport { LanguageSwitcher } from './LanguageSwitcher.js'\nexport type { LanguageSwitcherClassNames } from './LanguageSwitcher.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'\nexport type { LocaleMiddlewareResult } from './localeMiddleware.js'\nexport { buildLocalizationConfig } from './localizationConfig.js'\nexport { buildLocalizedPath, switchLocalePath } from './localizedPath.js'\nexport type { LocalizedSlugs } from './localizedPath.js'\nexport { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'\nexport { resolveLocalized } from './resolveLocalized.js'\nexport type { I18nConfig, LocaleDefinition } from './types.js'\nexport { validateI18nConfig } from './validation.js'\n"],"names":["AlternateLinksProvider","useAlternateLinks","useSetAlternateLinks","AlternateLinksUpdater","createProxy","DEFAULT_PROXY_MATCHER","getLocalizedSlugs","getDefaultLocale","getLocaleCodes","getLocaleDefinition","isValidLocale","LanguageSwitcher","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","buildLocalizationConfig","buildLocalizedPath","switchLocalePath","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","resolveLocalized","validateI18nConfig"],"mappings":"AAAA,SACEA,sBAAsB,EACtBC,iBAAiB,EACjBC,oBAAoB,QACf,6BAA4B;AAEnC,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,mBAAkB;AACrE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,aAAa,QAAQ,eAAc;AACnG,SAASC,gBAAgB,QAAQ,wBAAuB;AAExD,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,wBAAuB;AAE1F,SAASC,uBAAuB,QAAQ,0BAAyB;AACjE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,qBAAoB;AAEzE,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,eAAe,QAAQ,uBAAsB;AAC/F,SAASC,gBAAgB,QAAQ,wBAAuB;AAExD,SAASC,kBAAkB,QAAQ,kBAAiB"}
+13
View File
@@ -0,0 +1,13 @@
/**
* Resolves a possibly-localized value to a string for the given locale.
* Payload returns a localized field as a plain string (current locale) OR, with
* locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles
* both, with a safe fallback to the first available value — replacing the
* hand-rolled `getSafeString` with `any` copied into every project (JSON-LD,
* rich text, form topics, …).
*
* import { resolveLocalized } from '@intecion/ipal-kit'
* const name = resolveLocalized(item.label, locale) // '' if nothing
* const city = resolveLocalized(company.city, locale, '—') // custom fallback
*/
export declare function resolveLocalized(value: unknown, locale: string, fallback?: string): string;
+31
View File
@@ -0,0 +1,31 @@
/**
* Resolves a possibly-localized value to a string for the given locale.
* Payload returns a localized field as a plain string (current locale) OR, with
* locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles
* both, with a safe fallback to the first available value — replacing the
* hand-rolled `getSafeString` with `any` copied into every project (JSON-LD,
* rich text, form topics, …).
*
* import { resolveLocalized } from '@intecion/ipal-kit'
* const name = resolveLocalized(item.label, locale) // '' if nothing
* const city = resolveLocalized(company.city, locale, '—') // custom fallback
*/ export function resolveLocalized(value, locale, fallback = '') {
if (value == null) {
return fallback;
}
if (typeof value === 'string') {
return value;
}
if (typeof value === 'object') {
const map = value;
const forLocale = map[locale];
if (typeof forLocale === 'string') {
return forLocale;
}
const first = Object.values(map).find((v)=>typeof v === 'string');
return first ?? fallback;
}
return String(value);
}
//# sourceMappingURL=resolveLocalized.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/i18n/resolveLocalized.ts"],"sourcesContent":["/**\n * Resolves a possibly-localized value to a string for the given locale.\n * Payload returns a localized field as a plain string (current locale) OR, with\n * locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles\n * both, with a safe fallback to the first available value — replacing the\n * hand-rolled `getSafeString` with `any` copied into every project (JSON-LD,\n * rich text, form topics, …).\n *\n * import { resolveLocalized } from '@intecion/ipal-kit'\n * const name = resolveLocalized(item.label, locale) // '' if nothing\n * const city = resolveLocalized(company.city, locale, '—') // custom fallback\n */\nexport function resolveLocalized(value: unknown, locale: string, fallback = ''): string {\n if (value == null) {return fallback}\n if (typeof value === 'string') {return value}\n if (typeof value === 'object') {\n const map = value as Record<string, unknown>\n const forLocale = map[locale]\n if (typeof forLocale === 'string') {return forLocale}\n const first = Object.values(map).find((v) => typeof v === 'string')\n return (first) ?? fallback\n }\n return String(value)\n}\n"],"names":["resolveLocalized","value","locale","fallback","map","forLocale","first","Object","values","find","v","String"],"mappings":"AAAA;;;;;;;;;;;CAWC,GACD,OAAO,SAASA,iBAAiBC,KAAc,EAAEC,MAAc,EAAEC,WAAW,EAAE;IAC5E,IAAIF,SAAS,MAAM;QAAC,OAAOE;IAAQ;IACnC,IAAI,OAAOF,UAAU,UAAU;QAAC,OAAOA;IAAK;IAC5C,IAAI,OAAOA,UAAU,UAAU;QAC7B,MAAMG,MAAMH;QACZ,MAAMI,YAAYD,GAAG,CAACF,OAAO;QAC7B,IAAI,OAAOG,cAAc,UAAU;YAAC,OAAOA;QAAS;QACpD,MAAMC,QAAQC,OAAOC,MAAM,CAACJ,KAAKK,IAAI,CAAC,CAACC,IAAM,OAAOA,MAAM;QAC1D,OAAO,AAACJ,SAAUH;IACpB;IACA,OAAOQ,OAAOV;AAChB"}
+48
View File
@@ -0,0 +1,48 @@
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical';
import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react';
export type RenderRichTextProps = {
/** Wrapper class (e.g. Tailwind prose classes). */
className?: string;
/**
* Override the JSX for specific node types to apply the project's own
* styling. Receives Payload's defaultConverters; return the merged map.
* This is where a project puts its Tailwind classes per node (headings,
* paragraphs, links, …) — the design stays in the project, the parsing in
* the plugin's wrapper over Payload's official converter.
*/
converters?: JSXConvertersFunction;
/**
* Lexical editor state from a Payload richText field. Already localized —
* Payload returns the current locale's value, so NO per-locale key handling
* is needed here (unlike hand-rolled renderers that hardcode `.pl`).
*/
data: null | SerializedEditorState | undefined;
};
/**
* Renders a Payload Lexical richText field to React — a thin wrapper over
* Payload's OFFICIAL converter (@payloadcms/richtext-lexical/react).
*
* Why not hand-roll it: parsing Lexical by hand (node.type switch, node.format
* bit flags) duplicates what Payload already does, misses node types, drifts
* on Lexical updates, and tempts shortcuts like dangerouslySetInnerHTML (XSS)
* or a hardcoded `.pl` locale. The official converter handles every node,
* stays in sync, and is safe. This is the RenderBlocks of rich text: the
* plugin owns the engine, the project owns the look via `converters`.
*
* // project — a Server Component
* import { RenderRichText } from '@intecion/ipal-kit/rsc'
* <RenderRichText data={page.content} className="prose" />
*
* // with project styling per node:
* const converters: JSXConvertersFunction = ({ defaultConverters }) => ({
* ...defaultConverters,
* heading: ({ node, nodesToJSX }) => {
* const children = nodesToJSX({ nodes: node.children })
* const cls = { h2: 'text-2xl font-semibold mt-10', h3: 'text-xl mt-7' }[node.tag] ?? ''
* const Tag = node.tag as 'h1'|'h2'|'h3'|'h4'
* return <Tag className={cls}>{children}</Tag>
* },
* })
* <RenderRichText data={page.content} converters={converters} />
*/
export declare function RenderRichText({ className, converters, data }: RenderRichTextProps): import("react/jsx-runtime").JSX.Element | null;
+40
View File
@@ -0,0 +1,40 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { RichText as PayloadRichText } from '@payloadcms/richtext-lexical/react';
/**
* Renders a Payload Lexical richText field to React — a thin wrapper over
* Payload's OFFICIAL converter (@payloadcms/richtext-lexical/react).
*
* Why not hand-roll it: parsing Lexical by hand (node.type switch, node.format
* bit flags) duplicates what Payload already does, misses node types, drifts
* on Lexical updates, and tempts shortcuts like dangerouslySetInnerHTML (XSS)
* or a hardcoded `.pl` locale. The official converter handles every node,
* stays in sync, and is safe. This is the RenderBlocks of rich text: the
* plugin owns the engine, the project owns the look via `converters`.
*
* // project — a Server Component
* import { RenderRichText } from '@intecion/ipal-kit/rsc'
* <RenderRichText data={page.content} className="prose" />
*
* // with project styling per node:
* const converters: JSXConvertersFunction = ({ defaultConverters }) => ({
* ...defaultConverters,
* heading: ({ node, nodesToJSX }) => {
* const children = nodesToJSX({ nodes: node.children })
* const cls = { h2: 'text-2xl font-semibold mt-10', h3: 'text-xl mt-7' }[node.tag] ?? ''
* const Tag = node.tag as 'h1'|'h2'|'h3'|'h4'
* return <Tag className={cls}>{children}</Tag>
* },
* })
* <RenderRichText data={page.content} converters={converters} />
*/ export function RenderRichText({ className, converters, data }) {
if (!data) {
return null;
}
return /*#__PURE__*/ _jsx(PayloadRichText, {
className: className,
converters: converters,
data: data
});
}
//# sourceMappingURL=RenderRichText.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/richtext/RenderRichText.tsx"],"sourcesContent":["import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'\nimport type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'\n\nimport { RichText as PayloadRichText } from '@payloadcms/richtext-lexical/react'\n\nexport type RenderRichTextProps = {\n /** Wrapper class (e.g. Tailwind prose classes). */\n className?: string\n /**\n * Override the JSX for specific node types to apply the project's own\n * styling. Receives Payload's defaultConverters; return the merged map.\n * This is where a project puts its Tailwind classes per node (headings,\n * paragraphs, links, …) — the design stays in the project, the parsing in\n * the plugin's wrapper over Payload's official converter.\n */\n converters?: JSXConvertersFunction\n /**\n * Lexical editor state from a Payload richText field. Already localized —\n * Payload returns the current locale's value, so NO per-locale key handling\n * is needed here (unlike hand-rolled renderers that hardcode `.pl`).\n */\n data: null | SerializedEditorState | undefined\n}\n\n/**\n * Renders a Payload Lexical richText field to React — a thin wrapper over\n * Payload's OFFICIAL converter (@payloadcms/richtext-lexical/react).\n *\n * Why not hand-roll it: parsing Lexical by hand (node.type switch, node.format\n * bit flags) duplicates what Payload already does, misses node types, drifts\n * on Lexical updates, and tempts shortcuts like dangerouslySetInnerHTML (XSS)\n * or a hardcoded `.pl` locale. The official converter handles every node,\n * stays in sync, and is safe. This is the RenderBlocks of rich text: the\n * plugin owns the engine, the project owns the look via `converters`.\n *\n * // project — a Server Component\n * import { RenderRichText } from '@intecion/ipal-kit/rsc'\n * <RenderRichText data={page.content} className=\"prose\" />\n *\n * // with project styling per node:\n * const converters: JSXConvertersFunction = ({ defaultConverters }) => ({\n * ...defaultConverters,\n * heading: ({ node, nodesToJSX }) => {\n * const children = nodesToJSX({ nodes: node.children })\n * const cls = { h2: 'text-2xl font-semibold mt-10', h3: 'text-xl mt-7' }[node.tag] ?? ''\n * const Tag = node.tag as 'h1'|'h2'|'h3'|'h4'\n * return <Tag className={cls}>{children}</Tag>\n * },\n * })\n * <RenderRichText data={page.content} converters={converters} />\n */\nexport function RenderRichText({ className, converters, data }: RenderRichTextProps) {\n if (!data) {return null}\n return <PayloadRichText className={className} converters={converters} data={data} />\n}\n"],"names":["RichText","PayloadRichText","RenderRichText","className","converters","data"],"mappings":";AAGA,SAASA,YAAYC,eAAe,QAAQ,qCAAoC;AAqBhF;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,OAAO,SAASC,eAAe,EAAEC,SAAS,EAAEC,UAAU,EAAEC,IAAI,EAAuB;IACjF,IAAI,CAACA,MAAM;QAAC,OAAO;IAAI;IACvB,qBAAO,KAACJ;QAAgBE,WAAWA;QAAWC,YAAYA;QAAYC,MAAMA;;AAC9E"}
+2
View File
@@ -0,0 +1,2 @@
export { RenderRichText } from './RenderRichText.js';
export type { RenderRichTextProps } from './RenderRichText.js';
+3
View File
@@ -0,0 +1,3 @@
export { RenderRichText } from './RenderRichText.js';
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/richtext/index.ts"],"sourcesContent":["export { RenderRichText } from './RenderRichText.js'\nexport type { RenderRichTextProps } from './RenderRichText.js'\n"],"names":["RenderRichText"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAqB"}
+29
View File
@@ -0,0 +1,29 @@
type JsonLdSchema = Record<string, unknown>;
/**
* Renders one or more schema.org objects as a single JSON-LD @graph in a
* <script type="application/ld+json">. The plugin owns ONLY the wrapping and the
* safe serialization — NOT the schema contents. The project builds its own nodes
* (with the plugin's buildWebSiteJsonLd / buildOrganizationJsonLd /
* buildLocalBusinessJsonLd / buildSiteNavigationJsonLd helpers) and maps its own
* company data to the right @type.
*
* Why not a <GlobalJsonLd> that reads Company/Header: company data is a business
* domain that varies by country and industry (NIP/KRS in PL, ABN in AU, EIN in
* US; barAssociation for a law firm, licenceText for an HVAC business). A fixed
* model would be a leaky abstraction. So the project decides the @type and
* fields; the plugin just wraps and renders safely.
*
* // project — build nodes from YOUR data, choose the @type for YOUR market
* import { JsonLdGraph, buildWebSiteJsonLd, buildOrganizationJsonLd } from '@intecion/ipal-kit'
* const website = buildWebSiteJsonLd({ name, url })
* const org = buildOrganizationJsonLd({ name, url, logo })
* const localBusiness = { '@type': 'HVACBusiness', taxID: company.abn, areaServed: company.serviceArea, ... }
* <JsonLdGraph schemas={[website, org, localBusiness]} />
*
* Replaces the ~140-line JsonLd.tsx (only the @graph wrapper + <script> was
* actually duplicated; the schema mapping stays in the project where it belongs).
*/
export declare function JsonLdGraph({ schemas }: {
schemas: Array<JsonLdSchema | null | undefined>;
}): import("react/jsx-runtime").JSX.Element | null;
export {};
+44
View File
@@ -0,0 +1,44 @@
import { jsx as _jsx } from "react/jsx-runtime";
/**
* Renders one or more schema.org objects as a single JSON-LD @graph in a
* <script type="application/ld+json">. The plugin owns ONLY the wrapping and the
* safe serialization — NOT the schema contents. The project builds its own nodes
* (with the plugin's buildWebSiteJsonLd / buildOrganizationJsonLd /
* buildLocalBusinessJsonLd / buildSiteNavigationJsonLd helpers) and maps its own
* company data to the right @type.
*
* Why not a <GlobalJsonLd> that reads Company/Header: company data is a business
* domain that varies by country and industry (NIP/KRS in PL, ABN in AU, EIN in
* US; barAssociation for a law firm, licenceText for an HVAC business). A fixed
* model would be a leaky abstraction. So the project decides the @type and
* fields; the plugin just wraps and renders safely.
*
* // project — build nodes from YOUR data, choose the @type for YOUR market
* import { JsonLdGraph, buildWebSiteJsonLd, buildOrganizationJsonLd } from '@intecion/ipal-kit'
* const website = buildWebSiteJsonLd({ name, url })
* const org = buildOrganizationJsonLd({ name, url, logo })
* const localBusiness = { '@type': 'HVACBusiness', taxID: company.abn, areaServed: company.serviceArea, ... }
* <JsonLdGraph schemas={[website, org, localBusiness]} />
*
* Replaces the ~140-line JsonLd.tsx (only the @graph wrapper + <script> was
* actually duplicated; the schema mapping stays in the project where it belongs).
*/ export function JsonLdGraph({ schemas }) {
const graph = schemas.filter((s)=>Boolean(s));
if (graph.length === 0) {
return null;
}
const json = JSON.stringify({
'@context': 'https://schema.org',
'@graph': graph
});
return /*#__PURE__*/ _jsx("script", {
// Escape '<' to prevent the JSON from breaking out of the script tag
// (XSS hardening) — the only safety concern the plugin owns here.
dangerouslySetInnerHTML: {
__html: json.replace(/</g, '\\u003c')
},
type: "application/ld+json"
});
}
//# sourceMappingURL=JsonLdGraph.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/seo/JsonLdGraph.tsx"],"sourcesContent":["type JsonLdSchema = Record<string, unknown>\n\n/**\n * Renders one or more schema.org objects as a single JSON-LD @graph in a\n * <script type=\"application/ld+json\">. The plugin owns ONLY the wrapping and the\n * safe serialization — NOT the schema contents. The project builds its own nodes\n * (with the plugin's buildWebSiteJsonLd / buildOrganizationJsonLd /\n * buildLocalBusinessJsonLd / buildSiteNavigationJsonLd helpers) and maps its own\n * company data to the right @type.\n *\n * Why not a <GlobalJsonLd> that reads Company/Header: company data is a business\n * domain that varies by country and industry (NIP/KRS in PL, ABN in AU, EIN in\n * US; barAssociation for a law firm, licenceText for an HVAC business). A fixed\n * model would be a leaky abstraction. So the project decides the @type and\n * fields; the plugin just wraps and renders safely.\n *\n * // project — build nodes from YOUR data, choose the @type for YOUR market\n * import { JsonLdGraph, buildWebSiteJsonLd, buildOrganizationJsonLd } from '@intecion/ipal-kit'\n * const website = buildWebSiteJsonLd({ name, url })\n * const org = buildOrganizationJsonLd({ name, url, logo })\n * const localBusiness = { '@type': 'HVACBusiness', taxID: company.abn, areaServed: company.serviceArea, ... }\n * <JsonLdGraph schemas={[website, org, localBusiness]} />\n *\n * Replaces the ~140-line JsonLd.tsx (only the @graph wrapper + <script> was\n * actually duplicated; the schema mapping stays in the project where it belongs).\n */\nexport function JsonLdGraph({ schemas }: { schemas: Array<JsonLdSchema | null | undefined> }) {\n const graph = schemas.filter((s): s is JsonLdSchema => Boolean(s))\n if (graph.length === 0) {return null}\n\n const json = JSON.stringify({ '@context': 'https://schema.org', '@graph': graph })\n\n return (\n <script\n // Escape '<' to prevent the JSON from breaking out of the script tag\n // (XSS hardening) — the only safety concern the plugin owns here.\n dangerouslySetInnerHTML={{ __html: json.replace(/</g, '\\\\u003c') }}\n type=\"application/ld+json\"\n />\n )\n}\n"],"names":["JsonLdGraph","schemas","graph","filter","s","Boolean","length","json","JSON","stringify","script","dangerouslySetInnerHTML","__html","replace","type"],"mappings":";AAEA;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,SAASA,YAAY,EAAEC,OAAO,EAAuD;IAC1F,MAAMC,QAAQD,QAAQE,MAAM,CAAC,CAACC,IAAyBC,QAAQD;IAC/D,IAAIF,MAAMI,MAAM,KAAK,GAAG;QAAC,OAAO;IAAI;IAEpC,MAAMC,OAAOC,KAAKC,SAAS,CAAC;QAAE,YAAY;QAAsB,UAAUP;IAAM;IAEhF,qBACE,KAACQ;QACC,qEAAqE;QACrE,kEAAkE;QAClEC,yBAAyB;YAAEC,QAAQL,KAAKM,OAAO,CAAC,MAAM;QAAW;QACjEC,MAAK;;AAGX"}
+76
View File
@@ -0,0 +1,76 @@
/*
* Starter stylesheet for a sitemap served via buildSitemapXml({ cssUrl }).
* Uses type="text/css" on XML (W3C "Associating Style Sheets with XML") — NOT
* XSLT, so no browser deprecation warning. Selectors are the XML tag names.
*
* Copy to your project's /public/sitemap.css and adjust colors/spacing to taste.
* Crawlers ignore this; it only affects the human-readable browser view.
*/
urlset {
display: block;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #090d16;
color: #f1f5f9;
padding: 2rem 1.5rem;
max-width: 1200px;
margin: 0 auto;
line-height: 1.5;
}
/* Each URL entry as a card. */
url {
display: block;
background: #111827;
border: 1px solid #1e293b;
border-radius: 8px;
padding: 1rem 1.25rem;
margin-bottom: 0.75rem;
}
/* The URL itself. */
loc {
display: block;
font-size: 0.95rem;
font-weight: 600;
color: #f97316;
margin-bottom: 0.5rem;
word-break: break-all;
}
/* Metadata line: lastmod / changefreq / priority, each with a label. */
lastmod,
changefreq,
priority {
display: inline-block;
font-size: 0.8rem;
color: #94a3b8;
margin-right: 1.5rem;
}
lastmod::before {
content: 'Ostatnia modyfikacja: ';
color: #64748b;
}
changefreq::before {
content: 'Częstotliwość: ';
color: #64748b;
}
priority::before {
content: 'Priorytet: ';
color: #64748b;
}
/* hreflang alternates as small pills. */
link {
display: inline-block;
font-size: 0.75rem;
background: #1e293b;
color: #38bdf8;
border: 1px solid #334155;
padding: 0.15rem 0.45rem;
border-radius: 4px;
margin: 0.4rem 0.35rem 0 0;
}
+154
View File
@@ -0,0 +1,154 @@
/*
* Universal, minimalist & elegant stylesheet for XML Sitemap.
* Neutral palette with automatic dark and light mode support.
* W3C standard: type="text/css" on XML (zero browser deprecation warnings).
*
* Ships with @intecion/ipal-kit. Copy to /public/sitemap.css and adjust freely.
*/
:root {
--bg: #fafafa;
--card: #ffffff;
--border: #e5e7eb;
--border-hover: #d1d5db;
--text-main: #111827;
--text-secondary: #4b5563;
--text-muted: #9ca3af;
--url-color: #1e293b;
--badge-bg: #f3f4f6;
--badge-border: #e5e7eb;
--badge-text: #4b5563;
--accent: #027bd0;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #090a0f;
--card: #12131a;
--border: #1e202e;
--border-hover: #2e3247;
--text-main: #f9fafb;
--text-secondary: #9ca3af;
--text-muted: #6b7280;
--url-color: #f3f4f6;
--badge-bg: #1a1c26;
--badge-border: #282b3d;
--badge-text: #9ca3af;
--accent: #027bd0;
}
}
urlset {
display: flex;
flex-direction: column;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Inter, Helvetica, Arial, sans-serif;
background-color: var(--bg);
color: var(--text-main);
padding: 3rem 1.5rem;
max-width: 1040px;
margin: 0 auto;
min-height: 100vh;
box-sizing: border-box;
line-height: 1.5;
}
/* Minimalist header */
urlset::before {
content: "XML Sitemap";
display: block;
order: -2;
font-size: 1.35rem;
font-weight: 600;
letter-spacing: -0.02em;
color: var(--text-main);
padding-bottom: 0.4rem;
}
/* Brand note under the header — crafted by Intecion Group */
urlset::after {
content: "Intecion.com, Technology — engineered for modern digital experiences.";
display: block;
order: -1;
font-size: 0.8rem;
color: var(--text-muted);
padding-bottom: 1.25rem;
margin-bottom: 1.5rem;
border-bottom: 1px solid var(--border);
}
/* URL card */
url {
display: block;
width: 100%;
order: 0;
background-color: var(--card);
border: 1px solid var(--border);
border-radius: 8px;
padding: 1rem 1.25rem;
margin-bottom: 0.65rem;
box-sizing: border-box;
transition: border-color 0.15s ease, box-shadow 0.15s ease;
}
url:hover {
border-color: var(--border-hover);
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
}
/* URL address */
loc {
display: block;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
font-size: 0.875rem;
font-weight: 500;
color: var(--url-color);
word-break: break-all;
line-height: 1.45;
margin-bottom: 0.45rem;
}
/* Metadata row */
lastmod,
changefreq,
priority {
display: inline-block;
font-size: 0.775rem;
color: var(--text-secondary);
margin-right: 1.25rem;
margin-top: 0.15rem;
}
lastmod::before {
content: "Updated: ";
color: var(--text-muted);
}
changefreq::before {
content: "Frequency: ";
color: var(--text-muted);
}
priority::before {
content: "Priority: ";
color: var(--text-muted);
}
/* Alternate language pills */
link {
display: inline-block;
font-size: 0.7rem;
font-weight: 600;
background-color: var(--badge-bg);
border: 1px solid var(--badge-border);
color: var(--badge-text);
padding: 0.1rem 0.45rem;
border-radius: 4px;
margin-right: 0.3rem;
margin-top: 0.35rem;
text-transform: uppercase;
}
link::before {
content: attr(hreflang);
}
+33
View File
@@ -0,0 +1,33 @@
import type { BasePayload } from 'payload';
import type { I18nConfig } from '../i18n/index.js';
type ManifestIcon = {
sizes?: string;
src: string;
type?: string;
};
type Manifest = {
background_color?: string;
display: 'standalone';
icons: ManifestIcon[];
name?: string;
short_name?: string;
start_url: string;
theme_color?: string;
};
/**
* Builds a Next Web App Manifest from SiteSettings — replaces the ~50 lines of
* icon/mimeType parsing copied into every project's manifest.ts. Values come
* from the panel; missing fields are omitted (no hardcoded client data).
*
* // app/manifest.ts
* import { createManifestHandler } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* import { i18nConfig } from '@/i18n.config'
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
*/
export declare function createManifestHandler(opts: {
config: I18nConfig;
getCachedPayload: () => Promise<BasePayload>;
settingsSlug?: string;
}): () => Promise<Manifest>;
export {};
+65
View File
@@ -0,0 +1,65 @@
import { getDefaultLocale } from '../i18n/index.js';
/**
* Builds a Next Web App Manifest from SiteSettings — replaces the ~50 lines of
* icon/mimeType parsing copied into every project's manifest.ts. Values come
* from the panel; missing fields are omitted (no hardcoded client data).
*
* // app/manifest.ts
* import { createManifestHandler } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* import { i18nConfig } from '@/i18n.config'
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
*/ export function createManifestHandler(opts) {
return async ()=>{
const defaultLocale = getDefaultLocale(opts.config);
const payload = await opts.getCachedPayload();
const settings = await payload.findGlobal({
slug: opts.settingsSlug ?? 'site-settings',
depth: 1,
locale: defaultLocale
}).catch(()=>null);
const start_url = `/${defaultLocale}`;
if (!settings) {
return {
display: 'standalone',
icons: [],
start_url
};
}
const iconSource = settings.favicon ?? settings.logo;
const icons = [];
if (iconSource?.url) {
const type = iconSource.mimeType ?? (iconSource.url.endsWith('.svg') ? 'image/svg+xml' : undefined);
const isSvg = type === 'image/svg+xml';
const size = iconSource.width && iconSource.height ? `${iconSource.width}x${iconSource.height}` : undefined;
icons.push({
src: iconSource.url,
...isSvg ? {
sizes: 'any'
} : size ? {
sizes: size
} : {},
...type ? {
type
} : {}
});
}
return {
...settings.siteName ? {
name: settings.siteName,
short_name: settings.siteName
} : {},
display: 'standalone',
start_url,
...settings.backgroundColor ? {
background_color: settings.backgroundColor
} : {},
...settings.themeColor ? {
theme_color: settings.themeColor
} : {},
icons
};
};
}
//# sourceMappingURL=buildManifest.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/seo/buildManifest.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { getDefaultLocale } from '../i18n/index.js'\n\ntype MediaLike =\n | { height?: null | number; mimeType?: null | string; url?: null | string; width?: null | number }\n | null\n | undefined\n\ntype ManifestIcon = { sizes?: string; src: string; type?: string }\n\ntype Manifest = {\n background_color?: string\n display: 'standalone'\n icons: ManifestIcon[]\n name?: string\n short_name?: string\n start_url: string\n theme_color?: string\n}\n\ntype SettingsShape = {\n backgroundColor?: null | string\n favicon?: MediaLike\n logo?: MediaLike\n siteName?: null | string\n themeColor?: null | string\n}\n\n/**\n * Builds a Next Web App Manifest from SiteSettings — replaces the ~50 lines of\n * icon/mimeType parsing copied into every project's manifest.ts. Values come\n * from the panel; missing fields are omitted (no hardcoded client data).\n *\n * // app/manifest.ts\n * import { createManifestHandler } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export default createManifestHandler({ getCachedPayload, config: i18nConfig })\n */\nexport function createManifestHandler(opts: {\n config: I18nConfig\n getCachedPayload: () => Promise<BasePayload>\n settingsSlug?: string\n}): () => Promise<Manifest> {\n return async () => {\n const defaultLocale = getDefaultLocale(opts.config)\n const payload = await opts.getCachedPayload()\n const settings = (await payload\n .findGlobal({\n slug: (opts.settingsSlug ?? 'site-settings') as never,\n depth: 1,\n locale: defaultLocale as never,\n })\n .catch(() => null)) as null | SettingsShape\n\n const start_url = `/${defaultLocale}`\n if (!settings) {\n return { display: 'standalone', icons: [], start_url }\n }\n\n const iconSource = settings.favicon ?? settings.logo\n const icons: ManifestIcon[] = []\n if (iconSource?.url) {\n const type =\n iconSource.mimeType ?? (iconSource.url.endsWith('.svg') ? 'image/svg+xml' : undefined)\n const isSvg = type === 'image/svg+xml'\n const size =\n iconSource.width && iconSource.height\n ? `${iconSource.width}x${iconSource.height}`\n : undefined\n icons.push({\n src: iconSource.url,\n ...(isSvg ? { sizes: 'any' } : size ? { sizes: size } : {}),\n ...(type ? { type } : {}),\n })\n }\n\n return {\n ...(settings.siteName ? { name: settings.siteName, short_name: settings.siteName } : {}),\n display: 'standalone',\n start_url,\n ...(settings.backgroundColor ? { background_color: settings.backgroundColor } : {}),\n ...(settings.themeColor ? { theme_color: settings.themeColor } : {}),\n icons,\n }\n }\n}\n"],"names":["getDefaultLocale","createManifestHandler","opts","defaultLocale","config","payload","getCachedPayload","settings","findGlobal","slug","settingsSlug","depth","locale","catch","start_url","display","icons","iconSource","favicon","logo","url","type","mimeType","endsWith","undefined","isSvg","size","width","height","push","src","sizes","siteName","name","short_name","backgroundColor","background_color","themeColor","theme_color"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,mBAAkB;AA2BnD;;;;;;;;;;CAUC,GACD,OAAO,SAASC,sBAAsBC,IAIrC;IACC,OAAO;QACL,MAAMC,gBAAgBH,iBAAiBE,KAAKE,MAAM;QAClD,MAAMC,UAAU,MAAMH,KAAKI,gBAAgB;QAC3C,MAAMC,WAAY,MAAMF,QACrBG,UAAU,CAAC;YACVC,MAAOP,KAAKQ,YAAY,IAAI;YAC5BC,OAAO;YACPC,QAAQT;QACV,GACCU,KAAK,CAAC,IAAM;QAEf,MAAMC,YAAY,CAAC,CAAC,EAAEX,eAAe;QACrC,IAAI,CAACI,UAAU;YACb,OAAO;gBAAEQ,SAAS;gBAAcC,OAAO,EAAE;gBAAEF;YAAU;QACvD;QAEA,MAAMG,aAAaV,SAASW,OAAO,IAAIX,SAASY,IAAI;QACpD,MAAMH,QAAwB,EAAE;QAChC,IAAIC,YAAYG,KAAK;YACnB,MAAMC,OACJJ,WAAWK,QAAQ,IAAKL,CAAAA,WAAWG,GAAG,CAACG,QAAQ,CAAC,UAAU,kBAAkBC,SAAQ;YACtF,MAAMC,QAAQJ,SAAS;YACvB,MAAMK,OACJT,WAAWU,KAAK,IAAIV,WAAWW,MAAM,GACjC,GAAGX,WAAWU,KAAK,CAAC,CAAC,EAAEV,WAAWW,MAAM,EAAE,GAC1CJ;YACNR,MAAMa,IAAI,CAAC;gBACTC,KAAKb,WAAWG,GAAG;gBACnB,GAAIK,QAAQ;oBAAEM,OAAO;gBAAM,IAAIL,OAAO;oBAAEK,OAAOL;gBAAK,IAAI,CAAC,CAAC;gBAC1D,GAAIL,OAAO;oBAAEA;gBAAK,IAAI,CAAC,CAAC;YAC1B;QACF;QAEA,OAAO;YACL,GAAId,SAASyB,QAAQ,GAAG;gBAAEC,MAAM1B,SAASyB,QAAQ;gBAAEE,YAAY3B,SAASyB,QAAQ;YAAC,IAAI,CAAC,CAAC;YACvFjB,SAAS;YACTD;YACA,GAAIP,SAAS4B,eAAe,GAAG;gBAAEC,kBAAkB7B,SAAS4B,eAAe;YAAC,IAAI,CAAC,CAAC;YAClF,GAAI5B,SAAS8B,UAAU,GAAG;gBAAEC,aAAa/B,SAAS8B,UAAU;YAAC,IAAI,CAAC,CAAC;YACnErB;QACF;IACF;AACF"}
+16 -1
View File
@@ -17,12 +17,27 @@ export type PageMetadata = {
url: string;
}[];
locale?: string;
/** Site/brand name for the OG card. */
siteName?: string;
title: string;
/** 'website' | 'article' etc. Defaults to 'website'. */
type?: string;
/** Canonical URL of this page. */
url?: string;
};
/** robots directives — set to noindex/follow for legal/thin/search pages. */
/**
* robots directives. Indexed pages get generous snippet/preview limits by
* default (Google shows richer results); noindex pages get index:false.
*/
robots?: {
follow: boolean;
index: boolean;
/** 'none' | 'standard' | 'large' — image preview size in results. */
'max-image-preview'?: 'large' | 'none' | 'standard';
/** Max text snippet length; -1 = no limit. Next maps to max-snippet. */
'max-snippet'?: number;
/** Max video preview seconds; -1 = no limit. */
'max-video-preview'?: number;
};
title: string;
};
+20 -4
View File
@@ -71,16 +71,32 @@ import { buildHreflangAlternates } from './hreflang.js';
...images && {
images
},
locale
type: 'website',
locale,
...siteName ? {
siteName
} : {},
...canonical ? {
url: canonical
} : {}
},
// noindex → tell search engines to exclude the page but still follow links
// (authority flows through). For legal/thin/search-result pages.
// robots: noindex pages are excluded (follow keeps link authority). Indexed
// pages get generous snippet/preview limits so Google can show rich results
// (long snippets, large image previews, full video previews).
...meta?.noindex ? {
robots: {
follow: true,
index: false
}
} : {}
} : {
robots: {
follow: true,
index: true,
'max-image-preview': 'large',
'max-snippet': -1,
'max-video-preview': -1
}
}
};
}
File diff suppressed because one or more lines are too long
+29 -17
View File
@@ -1,33 +1,45 @@
import type { SitemapEntry } from './buildSitemapEntries.js';
type BuildSitemapXmlOptions = {
/**
* URL of a CSS stylesheet to make the sitemap readable in the browser, e.g.
* '/sitemap.css'. Uses `type="text/css"` — the W3C "Associating Style Sheets
* with XML" mechanism, which is NOT deprecated (unlike XSLT / type="text/xsl",
* which Chrome/WebKit are removing). CSS on XML shows no warning, styles the
* raw tags directly (e.g. `url { display: block }` turns the wall of text into
* cards), and crawlers ignore the directive entirely.
*/
cssUrl?: string;
};
/**
* Serializes sitemap entries to an XML STRING with an XSL stylesheet reference,
* so /sitemap.xml renders as a readable table in the browser (not raw XML) while
* staying a valid sitemap for crawlers.
* Serializes sitemap entries to a clean, indented XML STRING — valid for crawlers
* and (with `cssUrl`) styled in the browser via plain CSS.
*
* Why this exists alongside the Next MetadataRoute sitemap: Next's app/sitemap.ts
* (returning SitemapEntry[]) does NOT let you inject <?xml-stylesheet?>. To get
* the styled table, serve a custom route that returns this string instead:
* Two viewing modes:
* - No cssUrl → the browser's native formatted XML tree (indented, collapsible).
* - With cssUrl → a `<?xml-stylesheet type="text/css">` directive; the project's
* CSS styles the XML tags (cards, labels via ::before). NOT XSLT — that's being
* removed from browsers and shows a deprecation warning. CSS is safe and
* W3C-standard.
*
* // app/sitemap.xml/route.ts
* import { buildSitemapXml } from '@intecion/ipal-kit'
* import { sitemap } from '@/lib/content' // your entries source
* import { sitemap } from '@/lib/content'
* export const dynamic = 'force-dynamic'
* export async function GET() {
* const entries = await sitemap()
* const xml = buildSitemapXml(entries, { stylesheetUrl: '/sitemap.xsl' })
* const xml = buildSitemapXml(entries, { cssUrl: '/sitemap.css' })
* return new Response(xml, {
* headers: { 'Content-Type': 'application/xml; charset=utf-8' },
* })
* }
*
* Put sitemap.xsl in the project's /public (copy from the plugin's assets, or
* serve it from a route). The <?xml-stylesheet?> points browsers at it; crawlers
* ignore it and read the XML. Include hreflang alternates as <xhtml:link>.
* Put sitemap.css in the project's /public and style the tags (see docs/seo.md
* for a starter). Note: <loc> is an XML tag, not <a href> — CSS can't make it a
* clickable link (some browsers auto-detect URLs); the win is readability, not
* clickability.
*
* NOTE: if you use this custom route, DON'T also keep app/sitemap.ts — pick one
* (the styled route OR the Next MetadataRoute). Two sitemaps at different paths
* confuse crawlers.
* NOTE: if you use this custom route, DON'T also keep app/sitemap.ts — pick one.
* Two sitemaps confuse crawlers.
*/
export declare function buildSitemapXml(entries: SitemapEntry[], opts?: {
stylesheetUrl?: string;
}): string;
export declare function buildSitemapXml(entries: SitemapEntry[], opts?: BuildSitemapXmlOptions): string;
export {};
+18 -17
View File
@@ -1,33 +1,35 @@
/**
* Serializes sitemap entries to an XML STRING with an XSL stylesheet reference,
* so /sitemap.xml renders as a readable table in the browser (not raw XML) while
* staying a valid sitemap for crawlers.
* Serializes sitemap entries to a clean, indented XML STRING — valid for crawlers
* and (with `cssUrl`) styled in the browser via plain CSS.
*
* Why this exists alongside the Next MetadataRoute sitemap: Next's app/sitemap.ts
* (returning SitemapEntry[]) does NOT let you inject <?xml-stylesheet?>. To get
* the styled table, serve a custom route that returns this string instead:
* Two viewing modes:
* - No cssUrl → the browser's native formatted XML tree (indented, collapsible).
* - With cssUrl → a `<?xml-stylesheet type="text/css">` directive; the project's
* CSS styles the XML tags (cards, labels via ::before). NOT XSLT — that's being
* removed from browsers and shows a deprecation warning. CSS is safe and
* W3C-standard.
*
* // app/sitemap.xml/route.ts
* import { buildSitemapXml } from '@intecion/ipal-kit'
* import { sitemap } from '@/lib/content' // your entries source
* import { sitemap } from '@/lib/content'
* export const dynamic = 'force-dynamic'
* export async function GET() {
* const entries = await sitemap()
* const xml = buildSitemapXml(entries, { stylesheetUrl: '/sitemap.xsl' })
* const xml = buildSitemapXml(entries, { cssUrl: '/sitemap.css' })
* return new Response(xml, {
* headers: { 'Content-Type': 'application/xml; charset=utf-8' },
* })
* }
*
* Put sitemap.xsl in the project's /public (copy from the plugin's assets, or
* serve it from a route). The <?xml-stylesheet?> points browsers at it; crawlers
* ignore it and read the XML. Include hreflang alternates as <xhtml:link>.
* Put sitemap.css in the project's /public and style the tags (see docs/seo.md
* for a starter). Note: <loc> is an XML tag, not <a href> — CSS can't make it a
* clickable link (some browsers auto-detect URLs); the win is readability, not
* clickability.
*
* NOTE: if you use this custom route, DON'T also keep app/sitemap.ts — pick one
* (the styled route OR the Next MetadataRoute). Two sitemaps at different paths
* confuse crawlers.
* NOTE: if you use this custom route, DON'T also keep app/sitemap.ts — pick one.
* Two sitemaps confuse crawlers.
*/ export function buildSitemapXml(entries, opts = {}) {
const { stylesheetUrl } = opts;
const { cssUrl } = opts;
const esc = (s)=>s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
const urls = entries.map((e)=>{
const parts = [
@@ -39,7 +41,6 @@
}
if (e.changeFrequency) parts.push(` <changefreq>${e.changeFrequency}</changefreq>`);
if (typeof e.priority === 'number') parts.push(` <priority>${e.priority}</priority>`);
// hreflang alternates
const alternates = e.alternates?.languages;
if (alternates) {
for (const [lang, href] of Object.entries(alternates)){
@@ -50,7 +51,7 @@
}
return ` <url>\n${parts.join('\n')}\n </url>`;
}).join('\n');
const stylesheet = stylesheetUrl ? `<?xml-stylesheet type="text/xsl" href="${esc(stylesheetUrl)}"?>\n` : '';
const stylesheet = cssUrl ? `<?xml-stylesheet type="text/css" href="${esc(cssUrl)}"?>\n` : '';
return `<?xml version="1.0" encoding="UTF-8"?>\n` + stylesheet + `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" ` + `xmlns:xhtml="http://www.w3.org/1999/xhtml">\n` + urls + `\n</urlset>`;
}
File diff suppressed because one or more lines are too long
+3
View File
@@ -6,6 +6,7 @@ export { buildFaqJsonLd } from './buildFaqJsonLd.js';
export { buildIconsMetadata } from './buildIconsMetadata.js';
export { buildLlmsTxt } from './buildLlmsTxt.js';
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js';
export { createManifestHandler } from './buildManifest.js';
export { buildMetadata } from './buildMetadata.js';
export type { PageMetadata } from './buildMetadata.js';
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
@@ -24,8 +25,10 @@ export { createPageMetadata } from './createPageMetadata.js';
export { buildHreflangAlternates } from './hreflang.js';
export { injectAutoFillMeta } from './injectAutoFillMeta.js';
export { injectSeoTabs } from './injectSeoTabs.js';
export { JsonLdGraph } from './JsonLdGraph.js';
export { readSiteMetaConfig } from './readSiteMetaConfig.js';
export type { SiteMetaConfig } from './readSiteMetaConfig.js';
export { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js';
export { buildSeoPlugin } from './seoPluginConfig.js';
export { slugsAcrossLocales } from './slugsAcrossLocales.js';
export type { SeoMeta, SeoOption } from './types.js';
+3
View File
@@ -5,6 +5,7 @@ export { buildFaqJsonLd } from './buildFaqJsonLd.js';
export { buildIconsMetadata } from './buildIconsMetadata.js';
export { buildLlmsTxt } from './buildLlmsTxt.js';
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js';
export { createManifestHandler } from './buildManifest.js';
export { buildMetadata } from './buildMetadata.js';
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
export { buildRobots } from './buildRobots.js';
@@ -19,7 +20,9 @@ export { createPageMetadata } from './createPageMetadata.js';
export { buildHreflangAlternates } from './hreflang.js';
export { injectAutoFillMeta } from './injectAutoFillMeta.js';
export { injectSeoTabs } from './injectSeoTabs.js';
export { JsonLdGraph } from './JsonLdGraph.js';
export { readSiteMetaConfig } from './readSiteMetaConfig.js';
export { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js';
export { buildSeoPlugin } from './seoPluginConfig.js';
export { slugsAcrossLocales } from './slugsAcrossLocales.js';
export { validateFaviconField } from './validateFavicon.js';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","buildMetadata","buildOrganizationJsonLd","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","readSiteMetaConfig","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildOrganizationJsonLd","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
+40
View File
@@ -0,0 +1,40 @@
import type { BasePayload } from 'payload';
import type { I18nConfig } from '../i18n/index.js';
import type { SitemapEntry } from './buildSitemapEntries.js';
/**
* Ready-made Next route handler for /llms.txt. Replaces the ~60-line try/catch
* every project was copying. buildLlmsTxt already handles collections without
* drafts, so no workaround is needed here.
*
* // app/llms.txt/route.ts
* import { createLlmsTxtRoute } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* import { i18nConfig } from '@/i18n.config'
* export const dynamic = 'force-dynamic'
* export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })
*/
export declare function createLlmsTxtRoute(opts: {
baseUrl: string;
config: I18nConfig;
getCachedPayload: () => Promise<BasePayload>;
pagesSlug?: string;
settingsSlug?: string;
}): () => Promise<Response>;
/**
* Ready-made Next route handler for /sitemap.xml with the CSS stylesheet.
* Replaces the hand-written route in every project. Pass the project's `sitemap`
* helper (from createContentHelpers) and optionally a cssUrl.
*
* // app/sitemap.xml/route.ts
* import { createSitemapRouteHandler } from '@intecion/ipal-kit'
* import { sitemap } from '@/lib/content'
* export const dynamic = 'force-dynamic'
* export const GET = createSitemapRouteHandler(sitemap, { cssUrl: '/sitemap.css' })
*
* Remember: if you use this, DON'T also keep app/sitemap.ts (two sitemaps
* confuse crawlers).
*/
export declare function createSitemapRouteHandler(sitemap: () => Promise<SitemapEntry[]>, opts?: {
cssUrl?: string;
}): () => Promise<Response>;
+81
View File
@@ -0,0 +1,81 @@
import { buildLlmsTxt } from './buildLlmsTxt.js';
import { buildSitemapXml } from './buildSitemapXml.js';
/**
* Ready-made Next route handler for /llms.txt. Replaces the ~60-line try/catch
* every project was copying. buildLlmsTxt already handles collections without
* drafts, so no workaround is needed here.
*
* // app/llms.txt/route.ts
* import { createLlmsTxtRoute } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* import { i18nConfig } from '@/i18n.config'
* export const dynamic = 'force-dynamic'
* export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })
*/ export function createLlmsTxtRoute(opts) {
return async ()=>{
try {
const payload = await opts.getCachedPayload();
const body = await buildLlmsTxt({
baseUrl: opts.baseUrl,
config: opts.config,
pagesSlug: opts.pagesSlug,
payload,
settingsSlug: opts.settingsSlug
});
return new Response(body, {
headers: {
'Content-Type': 'text/plain; charset=utf-8'
}
});
} catch (err) {
// DB unreachable at build (container) — return a minimal valid file so the
// route doesn't 500; it fills in at runtime. No per-project try/catch.
console.warn('[ipal] createLlmsTxtRoute: could not build llms.txt:', err);
return new Response('# llms.txt\n', {
headers: {
'Content-Type': 'text/plain; charset=utf-8'
}
});
}
};
}
/**
* Ready-made Next route handler for /sitemap.xml with the CSS stylesheet.
* Replaces the hand-written route in every project. Pass the project's `sitemap`
* helper (from createContentHelpers) and optionally a cssUrl.
*
* // app/sitemap.xml/route.ts
* import { createSitemapRouteHandler } from '@intecion/ipal-kit'
* import { sitemap } from '@/lib/content'
* export const dynamic = 'force-dynamic'
* export const GET = createSitemapRouteHandler(sitemap, { cssUrl: '/sitemap.css' })
*
* Remember: if you use this, DON'T also keep app/sitemap.ts (two sitemaps
* confuse crawlers).
*/ export function createSitemapRouteHandler(sitemap, opts = {}) {
return async ()=>{
try {
const entries = await sitemap();
const xml = buildSitemapXml(entries, {
cssUrl: opts.cssUrl
});
return new Response(xml, {
headers: {
'Content-Type': 'application/xml; charset=utf-8'
}
});
} catch (err) {
console.warn('[ipal] createSitemapRouteHandler: could not build sitemap:', err);
// Valid empty urlset so the route doesn't 500 during a DB-less build.
const empty = '<?xml version="1.0" encoding="UTF-8"?>\n' + '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>';
return new Response(empty, {
headers: {
'Content-Type': 'application/xml; charset=utf-8'
}
});
}
};
}
//# sourceMappingURL=routeHandlers.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/seo/routeHandlers.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\nimport type { SitemapEntry } from './buildSitemapEntries.js'\n\nimport { buildLlmsTxt } from './buildLlmsTxt.js'\nimport { buildSitemapXml } from './buildSitemapXml.js'\n\n/**\n * Ready-made Next route handler for /llms.txt. Replaces the ~60-line try/catch\n * every project was copying. buildLlmsTxt already handles collections without\n * drafts, so no workaround is needed here.\n *\n * // app/llms.txt/route.ts\n * import { createLlmsTxtRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })\n */\nexport function createLlmsTxtRoute(opts: {\n baseUrl: string\n config: I18nConfig\n getCachedPayload: () => Promise<BasePayload>\n pagesSlug?: string\n settingsSlug?: string\n}): () => Promise<Response> {\n return async () => {\n try {\n const payload = await opts.getCachedPayload()\n const body = await buildLlmsTxt({\n baseUrl: opts.baseUrl,\n config: opts.config,\n pagesSlug: opts.pagesSlug,\n payload,\n settingsSlug: opts.settingsSlug,\n })\n return new Response(body, {\n headers: { 'Content-Type': 'text/plain; charset=utf-8' },\n })\n } catch (err) {\n // DB unreachable at build (container) — return a minimal valid file so the\n // route doesn't 500; it fills in at runtime. No per-project try/catch.\n console.warn('[ipal] createLlmsTxtRoute: could not build llms.txt:', err)\n return new Response('# llms.txt\\n', {\n headers: { 'Content-Type': 'text/plain; charset=utf-8' },\n })\n }\n }\n}\n\n/**\n * Ready-made Next route handler for /sitemap.xml with the CSS stylesheet.\n * Replaces the hand-written route in every project. Pass the project's `sitemap`\n * helper (from createContentHelpers) and optionally a cssUrl.\n *\n * // app/sitemap.xml/route.ts\n * import { createSitemapRouteHandler } from '@intecion/ipal-kit'\n * import { sitemap } from '@/lib/content'\n * export const dynamic = 'force-dynamic'\n * export const GET = createSitemapRouteHandler(sitemap, { cssUrl: '/sitemap.css' })\n *\n * Remember: if you use this, DON'T also keep app/sitemap.ts (two sitemaps\n * confuse crawlers).\n */\nexport function createSitemapRouteHandler(\n sitemap: () => Promise<SitemapEntry[]>,\n opts: { cssUrl?: string } = {},\n): () => Promise<Response> {\n return async () => {\n try {\n const entries = await sitemap()\n const xml = buildSitemapXml(entries, { cssUrl: opts.cssUrl })\n return new Response(xml, {\n headers: { 'Content-Type': 'application/xml; charset=utf-8' },\n })\n } catch (err) {\n console.warn('[ipal] createSitemapRouteHandler: could not build sitemap:', err)\n // Valid empty urlset so the route doesn't 500 during a DB-less build.\n const empty =\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' +\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"></urlset>'\n return new Response(empty, {\n headers: { 'Content-Type': 'application/xml; charset=utf-8' },\n })\n }\n }\n}\n"],"names":["buildLlmsTxt","buildSitemapXml","createLlmsTxtRoute","opts","payload","getCachedPayload","body","baseUrl","config","pagesSlug","settingsSlug","Response","headers","err","console","warn","createSitemapRouteHandler","sitemap","entries","xml","cssUrl","empty"],"mappings":"AAKA,SAASA,YAAY,QAAQ,oBAAmB;AAChD,SAASC,eAAe,QAAQ,uBAAsB;AAEtD;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,mBAAmBC,IAMlC;IACC,OAAO;QACL,IAAI;YACF,MAAMC,UAAU,MAAMD,KAAKE,gBAAgB;YAC3C,MAAMC,OAAO,MAAMN,aAAa;gBAC9BO,SAASJ,KAAKI,OAAO;gBACrBC,QAAQL,KAAKK,MAAM;gBACnBC,WAAWN,KAAKM,SAAS;gBACzBL;gBACAM,cAAcP,KAAKO,YAAY;YACjC;YACA,OAAO,IAAIC,SAASL,MAAM;gBACxBM,SAAS;oBAAE,gBAAgB;gBAA4B;YACzD;QACF,EAAE,OAAOC,KAAK;YACZ,2EAA2E;YAC3E,uEAAuE;YACvEC,QAAQC,IAAI,CAAC,wDAAwDF;YACrE,OAAO,IAAIF,SAAS,gBAAgB;gBAClCC,SAAS;oBAAE,gBAAgB;gBAA4B;YACzD;QACF;IACF;AACF;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASI,0BACdC,OAAsC,EACtCd,OAA4B,CAAC,CAAC;IAE9B,OAAO;QACL,IAAI;YACF,MAAMe,UAAU,MAAMD;YACtB,MAAME,MAAMlB,gBAAgBiB,SAAS;gBAAEE,QAAQjB,KAAKiB,MAAM;YAAC;YAC3D,OAAO,IAAIT,SAASQ,KAAK;gBACvBP,SAAS;oBAAE,gBAAgB;gBAAiC;YAC9D;QACF,EAAE,OAAOC,KAAK;YACZC,QAAQC,IAAI,CAAC,8DAA8DF;YAC3E,sEAAsE;YACtE,MAAMQ,QACJ,6CACA;YACF,OAAO,IAAIV,SAASU,OAAO;gBACzBT,SAAS;oBAAE,gBAAgB;gBAAiC;YAC9D;QACF;IACF;AACF"}
+44 -4
View File
@@ -42,6 +42,50 @@ import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo
let config = {
...incomingConfig
};
// --- 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
// plugin is a PEER dependency imported dynamically — ipal-kit doesn't bundle
// it, so projects that opt out (twoFactor: false) needn't install it, and the
// import never runs under generate:importmap when 2FA is off. 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).');
}
try {
// Dynamic specifier via a variable so TS doesn't try to resolve this
// optional peer dependency at build time (it isn't in the plugin's own
// node_modules). Avoids TS2307 without @ts-expect-error; the module
// exists at runtime in projects that installed it.
// @ts-ignore
const mod = await import('@clocklimited/payload-2fa');
// The package exports `payloadTotp`; older/other builds may use
// `totpPlugin`. Accept either so a rename doesn't break us.
const totp = mod.payloadTotp ?? mod.totpPlugin;
if (typeof totp !== 'function') {
throw new Error('expected export payloadTotp (or totpPlugin) to be a function — ' + 'check the installed @clocklimited/payload-2fa version');
}
config = await totp({
collection: tf.collectionSlug ?? 'users',
forceSetup: true,
totp: {
issuer: tf.issuer
}
})(config);
} catch (err) {
throw new Error('[ipal] 2FA is enforced but @clocklimited/payload-2fa is not installed. ' + 'Run: pnpm add @clocklimited/payload-2fa — or set twoFactor: false to ' + `opt out (discouraged). Original error: ${String(err)}`);
}
}
// --- i18n ---
config.localization = buildLocalizationConfig(options.i18n);
// --- access: inject roles into the client's auth collection ---
@@ -88,10 +132,6 @@ import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo
buildCookieSettings(),
buildNotifications()
];
// --- endpoints ---
// Test-email endpoint (admin-only): POST /api/ipal/test-email sends a probe
// message through the currently selected transport, so the panel's "send
// test" button can confirm delivery without leaving the admin UI.
config.endpoints = [
...config.endpoints ?? [],
testEmailEndpoint
+1 -1
View File
File diff suppressed because one or more lines are too long
+27
View File
@@ -15,6 +15,17 @@ export type IpalOptions = {
* (admin > editor > user) into the client's auth collection.
*/
access?: AccessOption;
/**
* Custom admin panel route, e.g. '/its' instead of the default '/admin'.
* The plugin sets config.routes.admin. IMPORTANT: this alone isn't enough —
* the project must ALSO move its panel folder to match:
* app/(payload)/its/[[...segments]]/page.tsx (and the not-found). The plugin
* can't create files in the project's app/. See docs/security.md.
*
* This is obscurity, not security: it hides the panel from dumb bots scanning
* /admin, but real protection is strong auth + 2FA + rate limiting.
*/
adminRoute?: string;
/**
* Collections whose entries live under an archive page — blog posts, case
* studies, anything with a listing. Adds an "archive page" assignment per
@@ -45,4 +56,20 @@ export type IpalOptions = {
seo?: SeoOption;
/** Additional fields injected into SiteSettings global */
siteSettingsFields?: Field[];
/**
* Two-factor authentication (TOTP), ENFORCED for every user. Wires
* @clocklimited/payload-2fa with forceSetup — no per-project opt-out. Every
* user must configure an authenticator app after login; TOTP is checked before
* data access (not just the admin UI). Requires the peer dep installed and an
* issuer name (shown in the authenticator app).
*
* Pass `false` ONLY for a project that genuinely can't use 2FA (rare, discouraged)
* — default is enforced. See docs/security.md.
*/
twoFactor?: {
/** Auth collection slug. Defaults to 'users'. */
collectionSlug?: string;
/** Name shown in the authenticator app (e.g. company/site name). */
issuer: string;
} | false;
};
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { Field } from 'payload'\n\nimport type { AccessOption } from './modules/access/types.js'\nimport type { ContentOption } from './modules/content/types.js'\nimport type { FormsOption } from './modules/forms/types.js'\nimport type { I18nConfig } from './modules/i18n/types.js'\nimport type { PagesOption } from './modules/pages/types.js'\nimport type { SeoOption } from './modules/seo/types.js'\n\n/**\n * Configuration options for the IPAL plugin.\n * Passed by the client project in payload.config.ts.\n */\nexport type IpalOptions = {\n /**\n * Role-based access control. Injects a fixed `roles` field\n * (admin > editor > user) into the client's auth collection.\n */\n access?: AccessOption\n\n /**\n * Collections whose entries live under an archive page — blog posts, case\n * studies, anything with a listing. Adds an \"archive page\" assignment per\n * collection in SiteSettings; the assigned page's localized slug becomes the\n * URL segment (/pl/artykuly/moj-post, /en/articles/my-post). Requires `pages`.\n */\n content?: ContentOption\n\n /** Disable the plugin without uninstalling (keeps DB schema intact) */\n enabled?: boolean\n\n /**\n * Forms — form-builder collections (forms, form-submissions) plus the\n * callable submitForm (Turnstile + persistence + SMTP-from-panel email).\n */\n forms?: FormsOption\n\n /** Internationalization — locales, default locale, fallback behavior */\n i18n: I18nConfig\n\n /** Additional fields injected into SiteIntegrations global */\n integrationsFields?: Field[]\n\n /**\n * System-page assignments (homepage, privacy, cookies) in SiteSettings.\n * Provide the slug of the client's Pages collection to enable.\n */\n pages?: PagesOption\n\n /**\n * SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo)\n * and enables locale-aware metadata helpers.\n */\n seo?: SeoOption\n\n /** Additional fields injected into SiteSettings global */\n siteSettingsFields?: Field[]\n}\n"],"names":[],"mappings":"AASA;;;CAGC,GACD,WA4CC"}
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { Field } from 'payload'\n\nimport type { AccessOption } from './modules/access/types.js'\nimport type { ContentOption } from './modules/content/types.js'\nimport type { FormsOption } from './modules/forms/types.js'\nimport type { I18nConfig } from './modules/i18n/types.js'\nimport type { PagesOption } from './modules/pages/types.js'\nimport type { SeoOption } from './modules/seo/types.js'\n\n/**\n * Configuration options for the IPAL plugin.\n * Passed by the client project in payload.config.ts.\n */\nexport type IpalOptions = {\n /**\n * Role-based access control. Injects a fixed `roles` field\n * (admin > editor > user) into the client's auth collection.\n */\n access?: AccessOption\n\n /**\n * Custom admin panel route, e.g. '/its' instead of the default '/admin'.\n * The plugin sets config.routes.admin. IMPORTANT: this alone isn't enough —\n * the project must ALSO move its panel folder to match:\n * app/(payload)/its/[[...segments]]/page.tsx (and the not-found). The plugin\n * can't create files in the project's app/. See docs/security.md.\n *\n * This is obscurity, not security: it hides the panel from dumb bots scanning\n * /admin, but real protection is strong auth + 2FA + rate limiting.\n */\n adminRoute?: string\n\n /**\n * Collections whose entries live under an archive page — blog posts, case\n * studies, anything with a listing. Adds an \"archive page\" assignment per\n * collection in SiteSettings; the assigned page's localized slug becomes the\n * URL segment (/pl/artykuly/moj-post, /en/articles/my-post). Requires `pages`.\n */\n content?: ContentOption\n\n /** Disable the plugin without uninstalling (keeps DB schema intact) */\n enabled?: boolean\n\n /**\n * Forms — form-builder collections (forms, form-submissions) plus the\n * callable submitForm (Turnstile + persistence + SMTP-from-panel email).\n */\n forms?: FormsOption\n\n /** Internationalization — locales, default locale, fallback behavior */\n i18n: I18nConfig\n\n /** Additional fields injected into SiteIntegrations global */\n integrationsFields?: Field[]\n\n /**\n * System-page assignments (homepage, privacy, cookies) in SiteSettings.\n * Provide the slug of the client's Pages collection to enable.\n */\n pages?: PagesOption\n\n /**\n * SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo)\n * and enables locale-aware metadata helpers.\n */\n seo?: SeoOption\n\n /** Additional fields injected into SiteSettings global */\n siteSettingsFields?: Field[]\n\n /**\n * Two-factor authentication (TOTP), ENFORCED for every user. Wires\n * @clocklimited/payload-2fa with forceSetup — no per-project opt-out. Every\n * user must configure an authenticator app after login; TOTP is checked before\n * data access (not just the admin UI). Requires the peer dep installed and an\n * issuer name (shown in the authenticator app).\n *\n * Pass `false` ONLY for a project that genuinely can't use 2FA (rare, discouraged)\n * — default is enforced. See docs/security.md.\n */\n twoFactor?:\n | {\n /** Auth collection slug. Defaults to 'users'. */\n collectionSlug?: string\n /** Name shown in the authenticator app (e.g. company/site name). */\n issuer: string\n }\n | false\n}\n"],"names":[],"mappings":"AASA;;;CAGC,GACD,WA2EC"}
+171
View File
@@ -0,0 +1,171 @@
# Dostępność — widget a11y (WCAG)
Widget dostępności: pływający przycisk otwierający panel z opcjami dla osób z
niepełnosprawnościami (rozmiar tekstu, kontrast, skala szarości, podkreślone
linki, czytelna czcionka, wyłączenie animacji, duży kursor).
> **OPCJONALNY — nie dodawaj domyślnie.** Widget a11y jest wymagany prawnie
> TYLKO dla niektórych stron (podmioty publiczne, część e-commerce/usług objętych
> European Accessibility Act). Dla większości stron komercyjnych to OPCJA, nie
> obowiązek. Dodawaj GDY klient/projekt tego wymaga — nie na każdej stronie z
> automatu. W razie wątpliwości: zapytaj, czy strona podlega wymogom dostępności.
Wzorzec jak CookieBanner: provider + widget, wpinasz raz. Preferencje w cookie
(bez flash), stosowane jako atrybuty `data-a11y-*` na `<html>`.
> **Granica plugin/projekt:** plugin dostarcza MECHANIZM (widget, stan, cookie,
> atrybuty na html). Projekt dostarcza CSS reagujący na atrybuty — bo style
> zależą od designu projektu (kolory, czcionki, Tailwind). Plugin NIE narzuca
> stylów, żeby nie kolidować. Gotowy CSS do skopiowania niżej.
---
## 1. Wpięcie — Provider + Widget
```tsx
// app/(frontend)/[locale]/layout.tsx
import { AccessibilityProvider, AccessibilityWidget } from '@intecion/ipal-kit/client'
<AccessibilityProvider>
<body>
{children}
<AccessibilityWidget
classNames={{
button: 'a11y-button',
panel: 'a11y-panel',
row: 'a11y-row',
label: 'a11y-label',
control: 'a11y-control',
active: 'a11y-active',
resetButton: 'a11y-reset',
closeButton: 'a11y-close',
}}
texts={{ title: 'Dostępność', reset: 'Resetuj' }} // opcjonalne, PL domyślnie
/>
</body>
</AccessibilityProvider>
```
Widget jest bez stylów (jak CookieBanner) — classNames dopasowujesz do designu.
---
## 2. CSS reagujący na atrybuty (OBOWIĄZKOWE — projekt)
Widget ustawia atrybuty na `<html>`. Bez tego CSS nic się nie dzieje. Skopiuj do
globalnego CSS projektu (dostosuj do designu):
```css
/* Rozmiar tekstu */
html[data-a11y-text="1"] { font-size: 112.5%; }
html[data-a11y-text="2"] { font-size: 125%; }
html[data-a11y-text="3"] { font-size: 150%; }
/* Odstęp między liniami */
html[data-a11y-line="1"] * { line-height: 1.8 !important; }
html[data-a11y-line="2"] * { line-height: 2.2 !important; }
/* Kontrast wysoki */
html[data-a11y-contrast="high"] {
filter: contrast(1.4);
}
/* Kontrast odwrócony */
html[data-a11y-contrast="inverted"] {
filter: invert(1) hue-rotate(180deg);
}
html[data-a11y-contrast="inverted"] img,
html[data-a11y-contrast="inverted"] video {
filter: invert(1) hue-rotate(180deg); /* przywróć media */
}
/* Skala szarości */
html[data-a11y-grayscale="on"] { filter: grayscale(1); }
/* Uwaga: filter na html nie kumuluje się — jeśli łączysz kontrast+szarość,
zastosuj na body albo połącz w jednej regule. */
/* Podkreślone linki */
html[data-a11y-underline="on"] a { text-decoration: underline !important; }
/* Czytelna czcionka (podmień na swoją dyslexia-friendly / prostą) */
html[data-a11y-font="readable"] * {
font-family: Verdana, Tahoma, sans-serif !important;
letter-spacing: 0.02em;
}
/* Wyłączenie animacji */
html[data-a11y-motion="reduce"] *,
html[data-a11y-motion="reduce"] *::before,
html[data-a11y-motion="reduce"] *::after {
animation-duration: 0.001ms !important;
transition-duration: 0.001ms !important;
scroll-behavior: auto !important;
}
/* Duży kursor */
html[data-a11y-cursor="big"] * {
cursor: url('/cursors/big.svg') 4 4, auto !important;
}
```
Dostosuj wartości do projektu (kolory kontrastu, czcionka, kursor). To Twój CSS —
plugin tylko ustawia atrybuty.
> **Kontrast + filter:** wiele opcji używa `filter` na `<html>`. CSS `filter` na
> jednym elemencie NIE kumuluje wielu wartości z różnych reguł — ostatnia wygrywa.
> Jeśli chcesz łączyć (np. szarość + kontrast), zastosuj filtry na `body` z
> pełną wartością, albo zbuduj reguły kombinowane. Dla pojedynczych opcji działa
> bez problemu.
---
## 3. Bez flash (SSR) — opcjonalne
Domyślnie widget stosuje atrybuty po hydratacji (krótki flash przy ładowaniu,
jeśli użytkownik miał ustawienia). Żeby tego uniknąć, odczytaj cookie server-side
i ustaw atrybuty na `<html>` w SSR:
```tsx
// layout.tsx (server) — odczytaj cookie i ustaw atrybuty od razu
import { cookies } from 'next/headers'
import { A11Y_COOKIE, parseA11y, a11yAttributes } from '@intecion/ipal-kit'
const raw = (await cookies()).get(A11Y_COOKIE)?.value
const attrs = a11yAttributes(parseA11y(raw))
const htmlAttrs = Object.fromEntries(
Object.entries(attrs).filter(([, v]) => v !== null),
)
return <html lang={locale} {...htmlAttrs}>...</html>
```
Provider i tak re-aplikuje na kliencie i synchronizuje. To tylko eliminuje flash.
---
## 4. Osobny przycisk otwierający (opcjonalnie)
Widget ma wbudowany pływający przycisk. Jeśli chcesz otwierać panel z innego
miejsca (np. stopka „Dostępność"), użyj hooka:
```tsx
'use client'
import { useAccessibility } from '@intecion/ipal-kit/client'
// stan otwarcia trzymaj sam, albo rozbuduj widget — hook daje state/set/reset
```
---
## 5. Compliance — kiedy dostępność jest wymagana
Dostępność (WCAG) jest wymagana prawnie TYLKO dla części stron:
- **Podmioty publiczne** (urzędy, szkoły, instytucje) — ustawa o dostępności cyfrowej
- **Duże e-commerce / usługi** objęte European Accessibility Act (2019/882, od 2025)
- Strony, gdzie klient sam tego wymaga (polityka firmy, przetarg)
Dla **większości stron komercyjnych** (wizytówka, mała firma, katalog) widget a11y
to **opcja, nie obowiązek** — dodawaj gdy klient wymaga, nie z automatu.
Gdy dodajesz: widget sam w sobie NIE czyni strony w pełni dostępną — to pomoc dla
użytkownika. Pełna dostępność to też semantyczny HTML, alt teksty, nawigacja
klawiaturą, kontrast bazowy. Widget uzupełnia, nie zastępuje. Nie sprzedawaj
klientowi „mamy widget = jesteśmy zgodni z WCAG". Patrz wymagania-prawne.md.
+262
View File
@@ -0,0 +1,262 @@
<!--
SZABLON agents.md dla projektów na @intecion/ipal-kit.
UŻYCIE: skopiuj ten plik do ROOTA nowego projektu jako `agents.md` (albo
AGENTS.md). Agenci (Antigravity, Claude Code, Cursor) czytają go automatycznie.
NIE zostawiaj go w docs/ — musi być w katalogu głównym projektu.
Dostosuj tylko to, co oznaczone <!-- DOSTOSUJ -->; reszta to uniwersalne
reguły ekosystemu ipal-kit (nie zmieniaj bez powodu).
Źródło prawdy dla szczegółów: node_modules/@intecion/ipal-kit/docs/
-->
# Zasady i Standardy Projektowe — Payload CMS 3 + Next 16 + @intecion/ipal-kit
> **Projekt:** <!-- DOSTOSUJ: nazwa klienta, domena, rynek (PL/AU/US), branża -->
Niniejszy dokument stanowi bezwzględnie obowiązujące reguły pracy dla agenta (Antigravity) w niniejszym projekcie. Został sporządzony na podstawie dokumentacji w `/docs`. Każda zasada musi być ściśle przestrzegana, bez wyjątków i bez stosowania obejść/prowizorek.
---
## 1. ZASADA NADRZĘDNA: ipal-kit JEST OBOWIĄZKOWY
1. **Obowiązkowe użycie pluginu:**
- Każda funkcja dostarczana przez `@intecion/ipal-kit` (i18n, SEO, formularze, consent, email, slug, bezpieczeństwo, strony systemowe, storage R2, breadcrumbs, JSON-LD) **MUSI** być realizowana przez plugin.
- **NIGDY** nie twórz własnego kodu w projekcie dublującego możliwości pluginu.
2. **Sprawdzaj przed pisaniem:**
- Zanim napiszesz jakąkolwiek funkcję, helper czy komponent — sprawdź dokumentację w `node_modules/@intecion/ipal-kit/docs/` oraz definicje typów `.d.ts`. Jeśli funkcja istnieje w pluginie, **musisz** jej użyć.
3. **Gdy w pluginie czegoś brakuje:**
- **NIE** obchodź braku prowizorką ani własnym kodem w projekcie (to tworzy dług technologiczny i rozbieżności).
- **Zgłoś brak funkcji do rozbudowy pluginu**, zamiast łatać to lokalnie.
- Logika uniwersalna (przydatna w innych projektach) trafia do pluginu. W projekcie znajduje się **wyłącznie** specyfika danego klienta (jego bloki, wygląd, struktura danych).
4. **Gdy coś w pluginie nie działa:**
- **Zgłoś problem i błąd**, zamiast tworzyć ciche obejścia, prowizoryczne hooki czy hardkodowane patche.
---
## 2. KROK 0: INSTALACJA I DOSTĘP DO DOKUMENTACJI PLUGINU
1. **Utwórz `.npmrc` w katalogu projektu:**
```ini
legacy-peer-deps=true
@intecion:registry=https://git.intecion.net/api/packages/IntecionSoftware/npm/
```
*(Scoped override: tylko `@intecion/*` z Gitea, rejestr publiczny bez tokena).*
2. **Instalacja pluginu:**
```bash
pnpm add @intecion/ipal-kit
```
*(NIGDY nie instaluj z gita `git+https://...` — psuje React Client Manifest w Next).*
3. **Lokalizacja dokumentacji źródłowej:**
```bash
ls node_modules/@intecion/ipal-kit/docs/
```
Zawsze korzystaj z plików w `docs/` pluginu (`getting-started.md`, `seo.md`, `forms.md`, `email.md`, `storage.md`, `i18n.md`, `blocks.md`, `turnstile.md` itd.).
---
## 3. ABSOLUTNY ZAKAZ HARDKODOWANIA
### A. Treść i teksty:
- **ZAKAZ:** Tekst widoczny dla użytkownika wpisany w JSX, etykiety i komunikaty w kodzie, instrukcje `if (locale === 'pl')`, tablice z tekstami w kodzie.
- **WYMAGANE:** Każdy tekst pochodzi z pola `localized: true`, pobierany z panelu CMS.
- **Częsty błąd (ukryty hardkod w fallbacku):** `siteName || 'Nazwa Klienta'` lub `catch { return { name: 'Firma...' } }` to **niedopuszczalny hardkod**! Gdy brak danych z panelu/env: **pomiń pole** (np. `...(val ? { name: val } : {})`), nie wstawiaj danych klienta w fallbacku `||` ani w bloku `catch`.
### B. Obrazy i multimedia:
- **ZAKAZ:** `import logo from '@/assets/...'`, ścieżki `src="/images/..."`.
- **WYMAGANE:** Pole `type: 'upload', relationTo: 'media'`, renderowane z `media.url`. Do kolekcji `Media` obowiązkowo wepnij `normalizeFilenameHook`.
- **Preconnect:** Użyj `<MediaPreconnect />` z pluginu (czyta `R2_PUBLIC_URL` z env), nigdy sztywnego tagu `<link>` z domeną.
- **Favicon:** Użyj `buildIconsMetadata(settings.favicon)` z panelu (format PNG, nie ręczny SVG).
### C. Linki i routing:
- **ZAKAZ:** `href="/pl/kontakt"`, menu jako statyczna tablica w kodzie, oraz **sztywna mapa zlokalizowanych ścieżek** (`const localizedRoutes = {...}` — kardynalny antywzorzec).
- **WYMAGANE:** `getLocalizedSlugs` / `switchLocalePath` z bazy danych, `getSystemPagePath`, relacje `relationship -> pages` w panelu CMS.
### D. Konfiguracja i dane firmy:
- **ZAKAZ:** `locale as 'pl' | 'en'`, zaszyty slug kolekcji, dane firmy, NIP, adres, telefon w kodzie.
- **WYMAGANE:** Jedno źródło prawdy `i18n.config.ts`, `locale as never`, dane firmy z globala (np. `siteSettings` / `CompanyInfo`), infrastruktura wyłącznie w `.env`.
### E. Renderer bloków, kolekcje, formularze (częste błędy):
- **Renderer rich text:** ZAWSZE `RenderRichText` z pluginu (`@intecion/ipal-kit/rsc`, wrapper nad oficjalnym konwerterem Lexical). NIGDY własny parser Lexical (switch po node.type, flagi node.format, dangerouslySetInnerHTML, hardkod `.pl`). Styl przez `converters`. Patrz richtext.md.
- **Renderer bloków:** ZAWSZE `RenderBlocks` z pluginu + mapa `registry`. NIGDY własny `switch (block.blockType)` — to gadatliwe, bez enhanceProps, rośnie liniowo. Mapa deklaratywna, silnik z pluginu.
- **MINIMUM kolekcji, nie maksimum:** Domyślnie tylko rdzeń (pages, media, settings, navigation, footer + globale). Kolekcję treści (blog/produkty) TYLKO gdy klient JAWNIE wymaga. NIGDY nie twórz: `users` (WBUDOWANE w Payload — nie duplikuj!), `daneFirmy`/`settings` jako kolekcje (to GLOBALE), FAQ/hero/features jako kolekcje (to BLOKI). Test przed stworzeniem: lista rekordów + własny URL + jawna potrzeba + Payload nie ma wbudowanego. Patrz `kolekcje-katalog.md`.
- **Formularze z buildera:** ZAWSZE formularz z buildera w panelu (kolekcja Forms) + `submitForm`. NIGDY własny hardkodowany formularz z polami w JSX — omija Turnstile, rate-limit, consent RODO, powiadomienia. Turnstile: `TurnstileProvider` (siteKey raz w layoutcie) + `useTurnstile()` w formularzu.
- **ZAKAZ:** `locale as 'pl' | 'en'`, zaszyty slug kolekcji, dane firmy, NIP, adres, telefon w kodzie.
- **WYMAGANE:** Jedno źródło prawdy `i18n.config.ts`, `locale as never`, dane firmy z globala (np. `siteSettings` / `CompanyInfo`), infrastruktura wyłącznie w `.env`.
---
## 4. ARCHITEKTURA I STRUKTURA PROJEKTU
### A. Next 16 + Payload 3:
- **NIGDY nie twórz `middleware.ts`.** W Next 16 stosuje się **WYŁĄCZNIE `proxy.ts`** (funkcja `proxy`). Jeśli plik `middleware.ts` istnieje — usuń go natychmiast.
- **Struktura katalogów:**
```
src/
app/
(frontend)/
styles.css # Tailwind + @source na plugin
[locale]/
layout.tsx # root layout bez sztywnego <head>
not-found.tsx # 404 (treść z panelu)
[[...slug]]/
page.tsx # render stron z bloków (podwójne nawiasy!)
(payload)/ # panel admina
manifest.ts # PWA z panelu
sitemap.ts # z lib/content + export const dynamic = 'force-dynamic'
robots.ts # z lib/content
blocks/
<NazwaBloku>/
config.ts # schemat pól bloku
Component.tsx # render komponentu
registry.ts # mapa blockType -> komponent
collections/
Pages.ts # layout typu blocks
Media.ts # upload + normalizeFilenameHook
globals/ # siteSettings, siteIntegrations, navigation, footer
lib/
content.ts # createContentHelpers — JEDNO źródło
payload.ts # helpery projektu (getSettings...)
i18n.config.ts # locale — jedno źródło
payload.config.ts
proxy.ts # routing locale (NIE middleware.ts)
```
### B. Przepływ danych i zależności:
- **Brak cykli importów:** Warstwa niższa (bloki) **NIE** może importować warstwy wyższej (`lib/*`). Dane zewnętrzne (np. klucze Turnstile) przekazuj przez `enhanceProps` w `page.tsx`.
- **Dostęp do Payloada:** Jedno źródło `getCachedPayload` w `lib/content.ts`.
- **Server Components (RSC) domyślnie:** Pobieranie danych po stronie serwera; `'use client'` stosuj wyłącznie dla komponentów z lokalnym stanem/interakcją. Chroń wrażliwe moduły przez `import 'server-only'`.
### C. Kluczowe wymagania SEO i Renderingu:
1. **Brak jawnego `<head>` w layoutcie:** Sztywny `<head>` wypycha metatagi Next.js do `<body>`. Pozwól Next.js zarządzać nagłówkiem. `<MediaPreconnect />` umieszczaj w `<body>` (React 19 automatycznie hoistuje tag link do head).
2. **Wymagane ISR:** `export const revalidate = 3600` w `page.tsx` stron (zapobiega race condition streamingu metadanych i zapewnia TTFB ~20ms).
3. **Wymagane `generateStaticParams`:** W `[[...slug]]/page.tsx` eksportuj `generateStaticParams` z `lib/content` (`export { generateStaticParams } from '@/lib/content'`). Gwarantuje synchroniczne generowanie metadanych w `<head>` dla robotów.
4. **`htmlLimitedBots`:** Skonfiguruj w `next.config.ts` zgodnie z `seo.md`.
---
## 5. STANDARDY KODU I TYPOWANIA (POZIOM SENIOR)
1. **Zero `any` i zero `@ts-ignore`:**
- Zawsze typuj precyzyjnie. Jeśli kształt danych z zewnątrz jest nieznany, użyj `unknown` + zawężenie (type guard).
- Wyjątek: wąskie rzutowanie `as unknown as Record<string, unknown>` przy udokumentowanych rozbieżnościach generatora Payload (np. pole zlokalizowane przy `locale: 'all'`).
2. **Typy generowane:** Importuj typy z `@/payload-types` (`pnpm generate:types`), nie twórz ręcznych duplikatów interfejsów.
3. **Generyki przy wywołaniu:** Stosuj np. `getSiteSettings<SiteSetting>(payload)`, a nie rzutowanie `as SiteSetting` na wyniku.
4. **`satisfies` dla konfiguracji:** Używaj `as const satisfies I18nConfig`.
5. **Obsługa błędów:** Nigdy nie połykaj błędów (`catch {}`). Loguj konkretny komunikat i zwracaj kontrolowany błąd. Stosuj guard clauses (płaski kod).
6. **Transakcje i hooki:** W hookach Payload zawsze przekazuj `req` do kolejnych operacji bazodanowych. Chroń hooki przed nieskończonymi pętlami za pomocą flagi w `context` (np. `context.skip`). Przy `payload.find` pamiętaj o `overrideAccess: false`, jeśli operacja ma respektować uprawnienia usera.
---
## 6. NAZEWNICTWO I KONWENCJE
- **Foldery bloków i pliki kolekcji:** PascalCase (`blocks/HeroSection/`, `collections/Pages.ts`).
- **Pliki bloku:** `config.ts` + `Component.tsx` w jednym folderze.
- **Slugi kolekcji:** camelCase, liczba mnoga (`pages`, `blogPosts`, `products`).
- **Slugi bloków:** camelCase (`hero`, `textSection`). Klucz w `registry.ts` musi być identyczny ze slugiem bloku.
- **Wspólne nazwy pól (obowiązkowe w każdym projekcie):**
- Nagłówek: `heading`
- Podtytuł: `subheading`
- Treść: `body` (textarea) lub `content` (richText)
- Obraz: `image` (upload -> media)
- Przycisk CTA: `ctaLabel` (text, localized)
- Cel CTA: `ctaTarget` (relationship -> pages)
- Link zewn.: `url` (text)
- Zgoda prawna: `consent` (checkbox)
---
**Globale Company/Header/Footer → PROJEKT, nie plugin.** Model danych firmy różni się per kraj (NIP/PL, ABN/AU, EIN/US) i branżę. NIE szukaj buildCompanyGlobal w pluginie — zdefiniuj własny src/globals/Company.ts. Schema.org: klocki pluginu (buildOrganizationJsonLd...) + JsonLdGraph, zmapuj SWOJE dane na @type (LegalService/PL, HVACBusiness/AU). Patrz seo.md.
## 6b. WYMAGANIA PRAWNE (COMPLIANCE)
Każda strona (PL/EU) MUSI mieć: polityka prywatności, polityka cookies, baner
zgody cookies, zgoda RODO w formularzach. Plugin dostarcza MECHANIZM:
- **Strony polityk** → System Pages (role: privacyPolicy, cookiePolicy, termsOfService), linkowane przez `getSystemPagePath`.
- **Baner cookies** → CookieBanner + CookieButton + ConsentProvider (analytics/marketing gated — NIE ładują się przed zgodą).
- **Zgoda RODO** → checkbox `consent` w formularzu (enforcement server-side w submitForm).
- **Strony noindex** → polityki/regulamin zaznacz `noindex` w panelu SEO (kanibalizacja fraz).
- **Ochrona:** hook `buildPreventDeleteSystemPage` blokuje usunięcie strony systemowej.
Granica: MY dostarczamy mechanizm, TREŚĆ prawną (tekst polityk) tworzy klient/prawnik.
**Widget dostępności (a11y)** — OPCJONALNY, NIE dodawaj domyślnie. Wymagany tylko
dla podmiotów publicznych / części e-commerce (European Accessibility Act). Dla
zwykłych stron komercyjnych to opcja — dodawaj GDY klient wymaga (AccessibilityProvider
+ AccessibilityWidget + CSS projektu). Patrz `accessibility.md`.
Patrz `wymagania-prawne.md`.
## 6c. HOOKI PLUGINU (automatyzacja)
Wpinaj w kolekcje gdzie dotyczy (patrz `hooks.md`):
- **buildRevalidateHook** (afterChange/afterDelete) — ISR odświeżany po zapisie (redaktor od razu widzi zmianę). `revalidatePath` wstrzykiwany z projektu.
- **trackSlugHistoryHook** (beforeChange) — zmiana slug → zapis starego → projekt robi 301 (stary URL nie daje 404).
- **setPublishedAtHook** — auto-data publikacji (blog).
- **normalizeFilenameHook** — czyste nazwy plików (Media, obowiązkowo).
- **buildPreventDeleteSystemPage** / **buildValidateUniqueRole** — ochrona stron systemowych.
## 6d. BEZPIECZEŃSTWO (nagłówki)
- **buildSecurityHeaders** w next.config — HSTS, COOP, nosniff, Referrer-Policy (z automatu, uniwersalne).
- **buildCsp** — generator CSP z twardymi regułami (base-uri, object-src, frame-ancestors). Flagi: turnstile, analytics, youtube, r2Url. Wdrażaj przez `report-only` → sprawdź konsolę → `enforce`.
- **2FA WYMUSZONE** — `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy' } })` + `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`. Wymuszone dla WSZYSTKICH użytkowników (forceSetup), bez opcji wyłączenia per user. NIE ustawiaj `twoFactor: false` (chyba że klient wprost odmawia). Bez zależności = błąd buildu. Patrz security.md.
- **Ścieżka panelu** — `ipalKit({ adminRoute: '/its' })` ukrywa panel. WYMAGA przeniesienia folderu `app/(payload)/admin/` → `app/(payload)/its/`. To obscurity, nie security (2FA to prawdziwa ochrona).
- CSP zostaje w projekcie (domeny), ale skeleton z pluginu. NIE Trusted Types (psuje Turnstile/GA).
## 7. PODZIAŁ PRACY I RÓL
- **Antigravity (Agent):** Buduje architekturę, logikę, kolekcje, bloki, routing, edytowalność przez panel, integracje oraz dba o brak hardkodów.
- **Impeccable (osobne narzędzie):** Dopracowuje wygląd, system wizualny na bazie `PRODUCT.md` i `DESIGN.md`. Antigravity nie „dopieszcza" styli ad-hoc kosztem logiki i edytowalności.
- **Klient / Redaktor:** Samodzielnie zarządza każdą treścią z poziomu panelu CMS.
---
## 8. PROCEDURA RAPORTOWANIA DO PLUGINU
Jeśli w trakcie pracy:
1. Funkcja okaże się brakująca w `@intecion/ipal-kit`,
2. Wystąpi błąd wewnętrzny w bibliotece pluginu,
3. Pojawi się powtarzalna potrzeba biznesowa przydatna w wielu projektach,
**Należy natychmiast przygotować raport proponowanej zmiany/rozbudowy pluginu:**
- Dokładny opis problemu / brakującej funkcjonalności,
- Proponowany interfejs API / sygnatura funkcji lub konfiguracji,
- Uzasadnienie uniwersalności dla innych projektów.
**Nie wolno tworzyć cichej łaty w kodzie projektu.**
---
## 9. MAPA DOKUMENTACJI — gdzie szukać szczegółów
Ten plik to skondensowane reguły. Szczegóły w `node_modules/@intecion/ipal-kit/docs/`:
| Chcę... | Plik |
|---|---|
| Zbudować projekt od zera | `getting-started.md` |
| Strukturę, nazewnictwo, konwencje | `fundamenty-projektu.md` |
| Jakie kolekcje budować (minimum!) | `kolekcje-katalog.md` |
| SEO, metadane, sitemap, favicon, structured data, llms.txt | `seo.md` |
| Hooki (revalidate, slug history, ochrona) | `hooks.md` |
| Bezpieczeństwo, CSP, COOP | `security.md` |
| Formularze, Turnstile, submitForm | `forms.md`, `turnstile.md` |
| i18n, strona jednojęzyczna, ścieżki | `i18n.md` |
| Strony systemowe, routing | `pages.md` |
| Bloki, RenderBlocks | `blocks.md` |
| Media, R2, MediaPreconnect | `storage.md` |
| Email (SMTP/Graph) | `email.md` |
| Consent, cookies | `consent.md` |
| Deployment, ISR/SSG, Coolify | `deployment.md` |
| Wymagania prawne, compliance | `wymagania-prawne.md` |
| Filozofia CMS, edytowalność, Impeccable | `architektura-tresci.md` |
| Standardy kodu, antywzorce | `standardy-kodu.md` |
---
## 10. ZAPISZ REGUŁY PROJEKTU
Kluczowe ustalenia projektu (stack, decyzje, tryby stron) zapisz we własnym pliku
kontekstu (`agents.md` / `.agents/context/`), żeby nie gubić ich między sesjami.
Nie polegaj tylko na pamięci sesji.
+61 -1
View File
@@ -248,4 +248,64 @@ Jeśli klient później doda drugi język, to PRZEBUDOWA, nie przełącznik:
Warto to przewidzieć na starcie: jeśli jest szansa na drugi język, rozważ od razu
strukturę wielojęzyczną (z [locale]), nawet dla jednego locale — wtedy prefiks
`/pl` jest, ale dodanie języka to tylko config, nie przebudowa struktury.
`/pl` jest, ale dodanie języka to tylko config, nie przebudowa struktury.
## Przełącznik języka bez 404 (AlternateLinks + LanguageSwitcher)
Gdy slug różni się per język (`/pl/uslugi/karne` vs `/en/services/criminal`),
naiwny przełącznik (podmiana prefiksu `/pl` → `/en`) prowadzi do 404. Plugin
rozwiązuje to przez kontekst alternatywnych URL-i.
### Jak to działa
1. **AlternateLinksProvider** w layoutcie — trzyma URL-e per język bieżącej strony
2. **AlternateLinksUpdater** na każdej stronie — zgłasza jej alternatywne URL-e
(strona RSC wylicza je z resolveRoute/getLocalizedSlugs)
3. **LanguageSwitcher** — linkuje do poprawnych URL-i z kontekstu
### Wpięcie
```tsx
// layout.tsx
import { AlternateLinksProvider } from '@intecion/ipal-kit/client'
<AlternateLinksProvider>{children}</AlternateLinksProvider>
// page.tsx (RSC) — wylicz alternatywy z routingu
import { AlternateLinksUpdater } from '@intecion/ipal-kit/client'
const alternates = { pl: '/pl/uslugi/karne', en: '/en/services/criminal' }
return <>
<AlternateLinksUpdater links={alternates} />
{/* treść */}
</>
// header (client) — przełącznik, headless, classNames jak CookieBanner
import { LanguageSwitcher } from '@intecion/ipal-kit/client'
<LanguageSwitcher
config={i18nConfig}
currentLocale={locale}
classNames={{ root: '...', trigger: '...', menu: '...', item: '...', itemActive: '...' }}
/>
```
LanguageSwitcher jest BEZ stylów (classNames) — nie `variant="light|dark"`, żeby
pasował do każdego designu projektu. Locale bez znanego alternatywnego URL →
fallback na root `/{code}`.
> **Skąd alternates na stronie:** strona RSC już rozwiązuje trasę (resolveRoute);
> z tego samego źródła wylicz slugi per język (getLocalizedSlugs/buildLocalizedPath)
> i przekaż do AlternateLinksUpdater. To eliminuje własny AlternateLinksContext
> (~150 linii) kopiowany w projektach.
## Next matcher — MUSI być literałem inline
Next.js analizuje `config.matcher` STATYCZNIE (AST) — musi być literałem tablicy
w pliku proxy/middleware, nie importem/zmienną. Mimo że plugin eksportuje
`DEFAULT_PROXY_MATCHER`, Next może nie rozpoznać go jako importu. Bezpiecznie:
```ts
// proxy.ts — matcher INLINE (nie import)
export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] }
```
`DEFAULT_PROXY_MATCHER` używaj jako referencji wartości, ale jeśli Next narzeka
na matcher — wklej go inline. To ograniczenie Next, nie pluginu.

Some files were not shown because too many files have changed in this diff Show More