diff --git a/bin/ipal-skills.mjs b/bin/ipal-skills.mjs index 9b50f35..cc47f8c 100644 --- a/bin/ipal-skills.mjs +++ b/bin/ipal-skills.mjs @@ -6,8 +6,8 @@ // Only folders named ipal-* are touched; the project's own skills stay as they are. // ipal-* folders that no longer exist in the package are removed (renamed/retired skills). -import { cpSync, existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'node:fs' -import { dirname, join, resolve } from 'node:path' +import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs' +import { dirname, join, relative, resolve } from 'node:path' import { fileURLToPath } from 'node:url' const args = process.argv.slice(2) @@ -45,3 +45,17 @@ for (const name of retired) { if (!dryRun) rmSync(join(dest, name), { recursive: true, force: true }) } console.log(`${dryRun ? '[dry-run] ' : ''}${shipped.length} skill(s) → ${dest}`) + +// Skills ship .ts/.tsx templates and scripts. A Next tsconfig ("include": ["**/*.tsx"]) would +// type-check them as project code and break `tsc` / `next build` → they must be excluded. +const tsconfig = join(process.cwd(), 'tsconfig.json') +const top = relative(process.cwd(), dest).split(/[\\/]/)[0] +if (existsSync(tsconfig) && top && !top.startsWith('..')) { + const text = readFileSync(tsconfig, 'utf8') + const exclude = text.match(/"exclude"\s*:\s*\[([^\]]*)\]/)?.[1] ?? '' + if (!exclude.includes(top)) { + console.warn(`\n⚠ tsconfig.json does not exclude "${top}" — skill templates would be type-checked and break the build.`) + console.warn(` Add it: "exclude": ["node_modules", "${top}"]`) + process.exitCode = 1 + } +} diff --git a/dist/exports/admin.d.ts b/dist/exports/admin.d.ts index 7743eeb..7fbb2ff 100644 --- a/dist/exports/admin.d.ts +++ b/dist/exports/admin.d.ts @@ -1,7 +1,8 @@ +export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'; /** * Entry point: @intecion/ipal-kit/admin * - * Admin-panel UI components (white-label branding). Separate export so Payload's + * Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's * importMap can resolve them by a stable path when ipalKit injects * admin.components.graphics.Logo/Icon. */ diff --git a/dist/exports/admin.js b/dist/exports/admin.js index 5b91017..fb36e5a 100644 --- a/dist/exports/admin.js +++ b/dist/exports/admin.js @@ -1,7 +1,8 @@ +export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'; /** * Entry point: @intecion/ipal-kit/admin * - * Admin-panel UI components (white-label branding). Separate export so Payload's + * Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's * importMap can resolve them by a stable path when ipalKit injects * admin.components.graphics.Logo/Icon. */ export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'; diff --git a/dist/exports/admin.js.map b/dist/exports/admin.js.map index 25a6fa1..85c27cf 100644 --- a/dist/exports/admin.js.map +++ b/dist/exports/admin.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/exports/admin.ts"],"sourcesContent":["/**\n * Entry point: @intecion/ipal-kit/admin\n *\n * Admin-panel UI components (white-label branding). Separate export so Payload's\n * importMap can resolve them by a stable path when ipalKit injects\n * admin.components.graphics.Logo/Icon.\n */\nexport { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'\n"],"names":["AdminIcon","AdminLogo","IntecionCredit"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,SAAS,EAAEC,SAAS,EAAEC,cAAc,QAAQ,+BAA8B"} \ No newline at end of file +{"version":3,"sources":["../../src/exports/admin.ts"],"sourcesContent":["export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'\n/**\n * Entry point: @intecion/ipal-kit/admin\n *\n * Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's\n * importMap can resolve them by a stable path when ipalKit injects\n * admin.components.graphics.Logo/Icon.\n */\nexport { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'\n"],"names":["RowLabel","AdminIcon","AdminLogo","IntecionCredit"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,2CAA0C;AACnE;;;;;;CAMC,GACD,SAASC,SAAS,EAAEC,SAAS,EAAEC,cAAc,QAAQ,+BAA8B"} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts index ac8021c..a59dc59 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -1,70 +1,73 @@ -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'; -export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'; -export type { ContentCollectionOption, ContentOption, ResolvedRoute, } from './modules/content/index.js'; -export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent, } from './modules/content/index.js'; -export type { ArchiveEntries } from './modules/content/index.js'; -export type { SearchResult } from './modules/content/index.js'; -export { graphAdapter } from './modules/email/graphAdapter.js'; -export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'; -export { mailAdapter } from './modules/email/mailAdapter.js'; -export type { MailAdapterArgs } from './modules/email/mailAdapter.js'; -export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'; -export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'; -export { assertEnv, ipalEnvRules } from './modules/env/index.js'; -export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'; -export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'; -export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'; -export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.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 { createHealthRoute } from './modules/health/index.js'; -export { buildCrossLocaleFieldSync, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook, } from './modules/hooks/index.js'; +export { ipalKit } from './plugin.js'; +export type { IpalOptions } from './types.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 { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'; -export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance, LinkValue, ResolveLinkHrefOptions, } from './modules/links/index.js'; -export { createMcpRoute } from './modules/mcp/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'; export type { PagesOption, SystemPageRole } from './modules/pages/index.js'; export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'; +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 type { GlobalQueryOptions } from './modules/payload/index.js'; -export { getGlobal, getSiteIntegrations, getSiteSettings, SITE_INTEGRATIONS_SLUG, SITE_SETTINGS_SLUG, } from './modules/payload/index.js'; +export { getGlobal, getSiteSettings, getSiteIntegrations, SITE_SETTINGS_SLUG, SITE_INTEGRATIONS_SLUG, } from './modules/payload/index.js'; +export type { SeoOption, SeoMeta, PageMetadata } from './modules/seo/index.js'; +export { composeTitle, buildHreflangAlternates, buildMetadata, readSiteMetaConfig, slugsAcrossLocales, } from './modules/seo/index.js'; +export type { SiteMetaConfig } from './modules/seo/index.js'; +export type { ContentOption, ContentCollectionOption, ResolvedRoute } from './modules/content/index.js'; +export { createContentHelpers } from './modules/frontend/index.js'; +export { resolveRoute, resolveRedirect, resolveNotFoundPage, blocksToMarkdown, createMarkdownRenderer, markdownResponse, prefersMarkdown, markdownHref, MARKDOWN_PREFIX, searchContent, createSearchRoute, archiveFieldName, getArchiveEntries, buildArchivePath, buildEntryPath, parsePageParam, } from './modules/content/index.js'; +export type { ArchiveEntries } from './modules/content/index.js'; +export type { SearchResult } from './modules/content/index.js'; export { lexicalToMarkdown } from './modules/richtext/index.js'; +export type { AutoFillMapping, SitemapEntry, RobotsRules, RobotsOptions } from './modules/seo/index.js'; +export { buildAutoFillMetaHook, injectAutoFillMeta, createMetadataGenerator, createPageMetadata, buildSitemapEntries, buildRobots, AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, } from './modules/seo/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 { CONSENT_CATEGORIES, DEFAULT_CONSENT, ACCEPT_ALL_CONSENT, REJECT_ALL_CONSENT, CONSENT_COOKIE, CONSENT_VERSION, CONSENT_MAX_AGE, serializeConsent, parseConsent, setDefaultConsent, updateConsent, getConsentTexts, } from './modules/consent/index.js'; +export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'; +export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'; +export { graphAdapter } from './modules/email/graphAdapter.js'; +export { mailAdapter } from './modules/email/mailAdapter.js'; +export type { MailAdapterArgs } from './modules/email/mailAdapter.js'; +export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'; +export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'; +export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'; +export type { FormsOption, FormsCollectionOverrides, FormsFieldsOverride, } from './modules/forms/types.js'; +export { buildValidator, isEmail, required, email, minLength, maxLength, checked, pattern, custom, } from './modules/forms/validators.js'; +export type { Rule } from './modules/forms/validators.js'; +export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'; +export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'; +export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'; +export { createHealthRoute } from './modules/health/index.js'; +export { createMcpRoute } from './modules/mcp/index.js'; +export { assertEnv, ipalEnvRules } from './modules/env/index.js'; +export type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from './modules/env/index.js'; +export type { AnalyticsConfig } from './modules/analytics/index.js'; +export { getAnalyticsConfig } from './modules/analytics/index.js'; +export { buildSlugField, toSlug } from './modules/slug/index.js'; +export { createLlmsTxtRoute, createSitemapRouteHandler, createManifestHandler } from './modules/seo/index.js'; +export { getNotificationTexts, resolveFormMessage, NOTIFICATION_FALLBACK } from './modules/notifications/index.js'; export { buildSecurityHeaders } from './modules/security/index.js'; export { buildCsp } from './modules/security/index.js'; export type { BuildCspArgs } from './modules/security/index.js'; -export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'; -export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'; -export { buildHreflangAlternates, buildMetadata, composeTitle, readSiteMetaConfig, slugsAcrossLocales, } from './modules/seo/index.js'; -export type { SiteMetaConfig } from './modules/seo/index.js'; -export type { AutoFillMapping, RobotsOptions, RobotsRules, SitemapEntry, } from './modules/seo/index.js'; -export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, 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 { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js'; export { buildNoindexField } from './modules/seo/index.js'; +export { rowLabel } from './modules/admin-ui/index.js'; +export type { RowLabelProps } from './modules/admin-ui/index.js'; +export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'; +export type { LinkAppearance, LinkValue, BuildLinkFieldOptions, BuildLinksFieldOptions, ResolveLinkHrefOptions, } from './modules/links/index.js'; export { buildSpeakableJsonLd } from './modules/seo/index.js'; export { buildSummaryField } from './modules/seo/index.js'; -export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd, } from './modules/seo/index.js'; -export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd, } from './modules/seo/index.js'; +export { buildWebSiteJsonLd, buildBreadcrumbJsonLd, buildSiteNavigationJsonLd } from './modules/seo/index.js'; +export { buildLocalBusinessJsonLd, buildFaqJsonLd, buildServiceJsonLd } from './modules/seo/index.js'; export { buildArticleJsonLd } 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'; -export type { IpalOptions } from './types.js'; +export { normalizeFilename, normalizeFilenameHook, buildOptimizeUploadHook, buildOptimizeUploadField } from './modules/media/index.js'; +export type { OptimizeUploadOptions } from './modules/media/index.js'; +export { buildRevalidateHook, setPublishedAtHook, buildPreventDeleteSystemPage, buildValidateUniqueRole, trackSlugHistoryHook, buildCrossLocaleFieldSync } from './modules/hooks/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 { SecurityHeader, BuildSecurityHeadersArgs } from './modules/security/index.js'; +export type { NotificationTexts, FormNotificationTexts } from './modules/notifications/index.js'; diff --git a/dist/index.js b/dist/index.js index b673fcb..3f16d2e 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,58 +1,59 @@ +export { ipalKit } from './plugin.js'; +export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath } from './modules/i18n/index.js'; +export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/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 { getAnalyticsConfig } from './modules/analytics/index.js'; -export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, DEFAULT_CONSENT, getConsentTexts, parseConsent, REJECT_ALL_CONSENT, serializeConsent, setDefaultConsent, updateConsent } from './modules/consent/index.js'; -export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent } from './modules/content/index.js'; -export { graphAdapter } from './modules/email/graphAdapter.js'; -export { mailAdapter } from './modules/email/mailAdapter.js'; +export { getGlobal, getSiteSettings, getSiteIntegrations, SITE_SETTINGS_SLUG, SITE_INTEGRATIONS_SLUG } from './modules/payload/index.js'; +export { composeTitle, buildHreflangAlternates, buildMetadata, readSiteMetaConfig, slugsAcrossLocales } from './modules/seo/index.js'; +export { createContentHelpers } from './modules/frontend/index.js'; +export { resolveRoute, resolveRedirect, resolveNotFoundPage, blocksToMarkdown, createMarkdownRenderer, markdownResponse, prefersMarkdown, markdownHref, MARKDOWN_PREFIX, searchContent, createSearchRoute, archiveFieldName, getArchiveEntries, buildArchivePath, buildEntryPath, parsePageParam } from './modules/content/index.js'; +// Lexical → Markdown (pure, no React) — for AI-readable output. +export { lexicalToMarkdown } from './modules/richtext/index.js'; +export { buildAutoFillMetaHook, injectAutoFillMeta, createMetadataGenerator, createPageMetadata, buildSitemapEntries, buildRobots, AI_ASSISTANT_BOTS, AI_TRAINING_BOTS } from './modules/seo/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 { CONSENT_CATEGORIES, DEFAULT_CONSENT, ACCEPT_ALL_CONSENT, REJECT_ALL_CONSENT, CONSENT_COOKIE, CONSENT_VERSION, CONSENT_MAX_AGE, serializeConsent, parseConsent, setDefaultConsent, updateConsent, getConsentTexts } from './modules/consent/index.js'; // Imported straight from the file, NOT from ./modules/email/index.js — that // barrel re-exports sendEmail, which imports 'server-only' and would crash when // Payload loads the config (or runs generate:importmap) as a plain Node script. export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'; -// Boot-time environment validation (fail fast on misconfigured deploys). -export { assertEnv, ipalEnvRules } from './modules/env/index.js'; -// Panel-managed form analytics (config-time field builder). -export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'; +export { graphAdapter } from './modules/email/graphAdapter.js'; +export { mailAdapter } from './modules/email/mailAdapter.js'; export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'; -export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.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 { buildValidator, isEmail, required, email, minLength, maxLength, checked, pattern, custom } from './modules/forms/validators.js'; +export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'; +// Panel-managed form analytics (config-time field builder). +export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'; // Healthcheck route (Coolify/Docker liveness with a real DB round-trip). export { createHealthRoute } from './modules/health/index.js'; -export { buildCrossLocaleFieldSync, 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 { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'; // Read-only MCP server (Claude/agents connect to the site and query it). export { createMcpRoute } from './modules/mcp/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'; -export { getGlobal, getSiteIntegrations, getSiteSettings, SITE_INTEGRATIONS_SLUG, SITE_SETTINGS_SLUG } from './modules/payload/index.js'; -// Lexical → Markdown (pure, no React) — for AI-readable output. -export { lexicalToMarkdown } from './modules/richtext/index.js'; +// Boot-time environment validation (fail fast on misconfigured deploys). +export { assertEnv, ipalEnvRules } from './modules/env/index.js'; +export { getAnalyticsConfig } from './modules/analytics/index.js'; +export { buildSlugField, toSlug } from './modules/slug/index.js'; +export { createLlmsTxtRoute, createSitemapRouteHandler, createManifestHandler } from './modules/seo/index.js'; +export { getNotificationTexts, resolveFormMessage, NOTIFICATION_FALLBACK } from './modules/notifications/index.js'; export { buildSecurityHeaders } from './modules/security/index.js'; export { buildCsp } from './modules/security/index.js'; -export { buildHreflangAlternates, buildMetadata, composeTitle, readSiteMetaConfig, slugsAcrossLocales } from './modules/seo/index.js'; -export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, 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 { buildNoindexField } from './modules/seo/index.js'; +export { rowLabel } from './modules/admin-ui/index.js'; +export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'; export { buildSpeakableJsonLd } from './modules/seo/index.js'; export { buildSummaryField } from './modules/seo/index.js'; -export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js'; +export { buildWebSiteJsonLd, buildBreadcrumbJsonLd, buildSiteNavigationJsonLd } 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 { buildLocalBusinessJsonLd, buildFaqJsonLd, buildServiceJsonLd } from './modules/seo/index.js'; export { buildArticleJsonLd } 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'; +export { normalizeFilename, normalizeFilenameHook, buildOptimizeUploadHook, buildOptimizeUploadField } from './modules/media/index.js'; +export { buildRevalidateHook, setPublishedAtHook, buildPreventDeleteSystemPage, buildValidateUniqueRole, trackSlugHistoryHook, buildCrossLocaleFieldSync } from './modules/hooks/index.js'; +export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js'; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map index d740178..668e7fe 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type { AccessOption, Role } from './modules/access/index.js'\nexport {\n adminOnly,\n adminOnlyField,\n adminOrEditor,\n adminOrEditorField,\n adminOrSelf,\n authenticated,\n hasMinimumRole,\n isAdmin,\n isEditor,\n requireRole,\n requireRoleField,\n ROLE_HIERARCHY,\n} from './modules/access/index.js'\nexport {\n A11Y_COOKIE,\n A11Y_DEFAULT,\n a11yAttributes,\n parseA11y,\n serializeA11y,\n} from './modules/accessibility/index.js'\nexport type { A11yState } from './modules/accessibility/index.js'\nexport type { AnalyticsConfig } from './modules/analytics/index.js'\nexport { getAnalyticsConfig } from './modules/analytics/index.js'\nexport {\n ACCEPT_ALL_CONSENT,\n CONSENT_CATEGORIES,\n CONSENT_COOKIE,\n CONSENT_MAX_AGE,\n CONSENT_VERSION,\n DEFAULT_CONSENT,\n getConsentTexts,\n parseConsent,\n REJECT_ALL_CONSENT,\n serializeConsent,\n setDefaultConsent,\n updateConsent,\n} from './modules/consent/index.js'\nexport type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'\nexport type {\n ContentCollectionOption,\n ContentOption,\n ResolvedRoute,\n} from './modules/content/index.js'\nexport {\n archiveFieldName,\n blocksToMarkdown,\n buildArchivePath,\n buildEntryPath,\n createMarkdownRenderer,\n createSearchRoute,\n getArchiveEntries,\n MARKDOWN_PREFIX,\n markdownHref,\n markdownResponse,\n parsePageParam,\n prefersMarkdown,\n resolveNotFoundPage,\n resolveRedirect,\n resolveRoute,\n searchContent,\n} from './modules/content/index.js'\nexport type { ArchiveEntries } from './modules/content/index.js'\nexport type { SearchResult } from './modules/content/index.js'\nexport { graphAdapter } from './modules/email/graphAdapter.js'\nexport type { GraphAdapterArgs } from './modules/email/graphAdapter.js'\nexport { mailAdapter } from './modules/email/mailAdapter.js'\nexport type { MailAdapterArgs } from './modules/email/mailAdapter.js'\n// Imported straight from the file, NOT from ./modules/email/index.js — that\n// barrel re-exports sendEmail, which imports 'server-only' and would crash when\n// Payload loads the config (or runs generate:importmap) as a plain Node script.\nexport { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'\nexport type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'\n// Boot-time environment validation (fail fast on misconfigured deploys).\nexport { assertEnv, ipalEnvRules } from './modules/env/index.js'\nexport type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'\n// Panel-managed form analytics (config-time field builder).\nexport { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'\nexport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'\nexport type {\n FormsCollectionOverrides,\n FormsFieldsOverride,\n FormsOption,\n} from './modules/forms/types.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'\n// Validation rules are pure — exported server-side too, for re-validating a\n// submission inside a server action. (useForm/useContactForm are client-only →\n// '@intecion/ipal-kit/client'.)\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'\nexport { createContentHelpers } from './modules/frontend/index.js'\n// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).\nexport { createHealthRoute } from './modules/health/index.js'\nexport {\n buildCrossLocaleFieldSync,\n buildPreventDeleteSystemPage,\n buildRevalidateHook,\n buildValidateUniqueRole,\n setPublishedAtHook,\n trackSlugHistoryHook,\n} from './modules/hooks/index.js'\nexport type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'\nexport {\n buildLocalizedPath,\n getDefaultLocale,\n getLocaleCodes,\n getLocaleDefinition,\n getLocalizedSlugs,\n isValidLocale,\n LOCALE_COOKIE_NAME,\n matchAcceptLanguage,\n negotiateLocale,\n switchLocalePath,\n} from './modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from './modules/i18n/index.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'\nexport { resolveLocalized } from './modules/i18n/index.js'\nexport { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'\nexport type {\n BuildLinkFieldOptions,\n BuildLinksFieldOptions,\n LinkAppearance,\n LinkValue,\n ResolveLinkHrefOptions,\n} from './modules/links/index.js'\n// Read-only MCP server (Claude/agents connect to the site and query it).\nexport { createMcpRoute } from './modules/mcp/index.js'\nexport { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'\nexport {\n getNotificationTexts,\n NOTIFICATION_FALLBACK,\n resolveFormMessage,\n} from './modules/notifications/index.js'\nexport type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'\nexport type { PagesOption, SystemPageRole } from './modules/pages/index.js'\nexport { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'\nexport type { GlobalQueryOptions } from './modules/payload/index.js'\nexport {\n getGlobal,\n getSiteIntegrations,\n getSiteSettings,\n SITE_INTEGRATIONS_SLUG,\n SITE_SETTINGS_SLUG,\n} from './modules/payload/index.js'\n// Lexical → Markdown (pure, no React) — for AI-readable output.\nexport { lexicalToMarkdown } from './modules/richtext/index.js'\nexport { buildSecurityHeaders } from './modules/security/index.js'\n\nexport { buildCsp } from './modules/security/index.js'\nexport type { BuildCspArgs } from './modules/security/index.js'\nexport type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'\nexport type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'\nexport {\n buildHreflangAlternates,\n buildMetadata,\n composeTitle,\n readSiteMetaConfig,\n slugsAcrossLocales,\n} from './modules/seo/index.js'\nexport type { SiteMetaConfig } from './modules/seo/index.js'\nexport type {\n AutoFillMapping,\n RobotsOptions,\n RobotsRules,\n SitemapEntry,\n} from './modules/seo/index.js'\nexport {\n AI_ASSISTANT_BOTS,\n AI_TRAINING_BOTS,\n buildAutoFillMetaHook,\n buildRobots,\n buildSitemapEntries,\n createMetadataGenerator,\n createPageMetadata,\n injectAutoFillMeta,\n} from './modules/seo/index.js'\nexport {\n createLlmsTxtRoute,\n createManifestHandler,\n createSitemapRouteHandler,\n} from './modules/seo/index.js'\nexport {\n buildIconsMetadata,\n buildOrganizationJsonLd,\n validateFaviconField,\n} from './modules/seo/index.js'\nexport { buildNoindexField } from './modules/seo/index.js'\nexport { buildSpeakableJsonLd } from './modules/seo/index.js'\nexport { buildSummaryField } from './modules/seo/index.js'\nexport {\n buildBreadcrumbJsonLd,\n buildSiteNavigationJsonLd,\n buildWebSiteJsonLd,\n} from './modules/seo/index.js'\n// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.\nexport {\n buildFaqJsonLd,\n buildLocalBusinessJsonLd,\n buildServiceJsonLd,\n} from './modules/seo/index.js'\nexport { buildArticleJsonLd } from './modules/seo/index.js'\nexport { buildLlmsTxt } from './modules/seo/index.js'\nexport { buildSitemapXml } from './modules/seo/index.js'\nexport { buildSlugField, toSlug } from './modules/slug/index.js'\nexport { buildR2Storage } from './modules/storage/index.js'\nexport { ipalKit } from './plugin.js'\nexport type { IpalOptions } from './types.js'\n"],"names":["adminOnly","adminOnlyField","adminOrEditor","adminOrEditorField","adminOrSelf","authenticated","hasMinimumRole","isAdmin","isEditor","requireRole","requireRoleField","ROLE_HIERARCHY","A11Y_COOKIE","A11Y_DEFAULT","a11yAttributes","parseA11y","serializeA11y","getAnalyticsConfig","ACCEPT_ALL_CONSENT","CONSENT_CATEGORIES","CONSENT_COOKIE","CONSENT_MAX_AGE","CONSENT_VERSION","DEFAULT_CONSENT","getConsentTexts","parseConsent","REJECT_ALL_CONSENT","serializeConsent","setDefaultConsent","updateConsent","archiveFieldName","blocksToMarkdown","buildArchivePath","buildEntryPath","createMarkdownRenderer","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","markdownResponse","parsePageParam","prefersMarkdown","resolveNotFoundPage","resolveRedirect","resolveRoute","searchContent","graphAdapter","mailAdapter","panelSmtpAdapter","assertEnv","ipalEnvRules","buildFormAnalyticsFields","buildFormsPlugin","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","createContentHelpers","createHealthRoute","buildCrossLocaleFieldSync","buildPreventDeleteSystemPage","buildRevalidateHook","buildValidateUniqueRole","setPublishedAtHook","trackSlugHistoryHook","buildLocalizedPath","getDefaultLocale","getLocaleCodes","getLocaleDefinition","getLocalizedSlugs","isValidLocale","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","switchLocalePath","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","createProxy","DEFAULT_PROXY_MATCHER","resolveLocalized","buildLinkField","buildLinksField","resolveLinkHref","createMcpRoute","normalizeFilename","normalizeFilenameHook","getNotificationTexts","NOTIFICATION_FALLBACK","resolveFormMessage","ALL_SYSTEM_PAGE_ROLES","getSystemPagePath","getGlobal","getSiteIntegrations","getSiteSettings","SITE_INTEGRATIONS_SLUG","SITE_SETTINGS_SLUG","lexicalToMarkdown","buildSecurityHeaders","buildCsp","buildHreflangAlternates","buildMetadata","composeTitle","readSiteMetaConfig","slugsAcrossLocales","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildAutoFillMetaHook","buildRobots","buildSitemapEntries","createMetadataGenerator","createPageMetadata","injectAutoFillMeta","createLlmsTxtRoute","createManifestHandler","createSitemapRouteHandler","buildIconsMetadata","buildOrganizationJsonLd","validateFaviconField","buildNoindexField","buildSpeakableJsonLd","buildSummaryField","buildBreadcrumbJsonLd","buildSiteNavigationJsonLd","buildWebSiteJsonLd","buildFaqJsonLd","buildLocalBusinessJsonLd","buildServiceJsonLd","buildArticleJsonLd","buildLlmsTxt","buildSitemapXml","buildSlugField","toSlug","buildR2Storage","ipalKit"],"mappings":"AACA,SACEA,SAAS,EACTC,cAAc,EACdC,aAAa,EACbC,kBAAkB,EAClBC,WAAW,EACXC,aAAa,EACbC,cAAc,EACdC,OAAO,EACPC,QAAQ,EACRC,WAAW,EACXC,gBAAgB,EAChBC,cAAc,QACT,4BAA2B;AAClC,SACEC,WAAW,EACXC,YAAY,EACZC,cAAc,EACdC,SAAS,EACTC,aAAa,QACR,mCAAkC;AAGzC,SAASC,kBAAkB,QAAQ,+BAA8B;AACjE,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,eAAe,EACf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C,kBAAkB,QACb,yBAAwB;AAC/B,SAASC,kBAAkB,QAAQ,yBAAwB;AAC3D,SAASC,YAAY,QAAQ,yBAAwB;AACrD,SAASC,eAAe,QAAQ,yBAAwB;AACxD,SAASC,cAAc,EAAEC,MAAM,QAAQ,0BAAyB;AAChE,SAASC,cAAc,QAAQ,6BAA4B;AAC3D,SAASC,OAAO,QAAQ,cAAa"} \ No newline at end of file +{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export { ipalKit } from './plugin.js'\nexport type { IpalOptions } from './types.js'\nexport type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'\nexport {\n buildLocalizedPath,\n getDefaultLocale,\n getLocaleCodes,\n getLocaleDefinition,\n getLocalizedSlugs,\n isValidLocale,\n LOCALE_COOKIE_NAME,\n matchAcceptLanguage,\n negotiateLocale,\n switchLocalePath,\n} from './modules/i18n/index.js'\nexport type { PagesOption, SystemPageRole } from './modules/pages/index.js'\nexport { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'\nexport type { AccessOption, Role } from './modules/access/index.js'\nexport {\n adminOnly,\n adminOnlyField,\n adminOrEditor,\n adminOrEditorField,\n adminOrSelf,\n authenticated,\n hasMinimumRole,\n isAdmin,\n isEditor,\n requireRole,\n requireRoleField,\n ROLE_HIERARCHY,\n} from './modules/access/index.js'\nexport type { GlobalQueryOptions } from './modules/payload/index.js'\nexport {\n getGlobal,\n getSiteSettings,\n getSiteIntegrations,\n SITE_SETTINGS_SLUG,\n SITE_INTEGRATIONS_SLUG,\n} from './modules/payload/index.js'\nexport type { SeoOption, SeoMeta, PageMetadata } from './modules/seo/index.js'\nexport {\n composeTitle,\n buildHreflangAlternates,\n buildMetadata,\n readSiteMetaConfig,\n slugsAcrossLocales,\n} from './modules/seo/index.js'\nexport type { SiteMetaConfig } from './modules/seo/index.js'\nexport type { ContentOption, ContentCollectionOption, ResolvedRoute } from './modules/content/index.js'\nexport { createContentHelpers } from './modules/frontend/index.js'\nexport {\n resolveRoute,\n resolveRedirect,\n resolveNotFoundPage,\n blocksToMarkdown,\n createMarkdownRenderer,\n markdownResponse,\n prefersMarkdown,\n markdownHref,\n MARKDOWN_PREFIX,\n searchContent,\n createSearchRoute,\n archiveFieldName,\n getArchiveEntries,\n buildArchivePath,\n buildEntryPath,\n parsePageParam,\n} from './modules/content/index.js'\nexport type { ArchiveEntries } from './modules/content/index.js'\nexport type { SearchResult } from './modules/content/index.js'\n// Lexical → Markdown (pure, no React) — for AI-readable output.\nexport { lexicalToMarkdown } from './modules/richtext/index.js'\nexport type { AutoFillMapping, SitemapEntry, RobotsRules, RobotsOptions } from './modules/seo/index.js'\nexport {\n buildAutoFillMetaHook,\n injectAutoFillMeta,\n createMetadataGenerator,\n createPageMetadata,\n buildSitemapEntries,\n buildRobots,\n AI_ASSISTANT_BOTS,\n AI_TRAINING_BOTS,\n} from './modules/seo/index.js'\nexport type { LocaleMiddlewareResult } from './modules/i18n/index.js'\nexport {\n createLocaleMiddleware,\n DEFAULT_MIDDLEWARE_MATCHER,\n} from './modules/i18n/index.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'\nexport { resolveLocalized } from './modules/i18n/index.js'\nexport {\n CONSENT_CATEGORIES,\n DEFAULT_CONSENT,\n ACCEPT_ALL_CONSENT,\n REJECT_ALL_CONSENT,\n CONSENT_COOKIE,\n CONSENT_VERSION,\n CONSENT_MAX_AGE,\n serializeConsent,\n parseConsent,\n setDefaultConsent,\n updateConsent,\n getConsentTexts,\n} from './modules/consent/index.js'\nexport type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'\n// Imported straight from the file, NOT from ./modules/email/index.js — that\n// barrel re-exports sendEmail, which imports 'server-only' and would crash when\n// Payload loads the config (or runs generate:importmap) as a plain Node script.\nexport { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'\nexport { graphAdapter } from './modules/email/graphAdapter.js'\nexport { mailAdapter } from './modules/email/mailAdapter.js'\nexport type { MailAdapterArgs } from './modules/email/mailAdapter.js'\nexport type { GraphAdapterArgs } from './modules/email/graphAdapter.js'\nexport type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'\nexport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nexport type {\n FormsOption,\n FormsCollectionOverrides,\n FormsFieldsOverride,\n} from './modules/forms/types.js'\n// Validation rules are pure — exported server-side too, for re-validating a\n// submission inside a server action. (useForm/useContactForm are client-only →\n// '@intecion/ipal-kit/client'.)\nexport {\n buildValidator,\n isEmail,\n required,\n email,\n minLength,\n maxLength,\n checked,\n pattern,\n custom,\n} from './modules/forms/validators.js'\nexport type { Rule } from './modules/forms/validators.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'\n// Panel-managed form analytics (config-time field builder).\nexport { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'\n// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).\nexport { createHealthRoute } from './modules/health/index.js'\n// Read-only MCP server (Claude/agents connect to the site and query it).\nexport { createMcpRoute } from './modules/mcp/index.js'\n// Boot-time environment validation (fail fast on misconfigured deploys).\nexport { assertEnv, ipalEnvRules } from './modules/env/index.js'\nexport type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from './modules/env/index.js'\nexport type { AnalyticsConfig } from './modules/analytics/index.js'\nexport { getAnalyticsConfig } from './modules/analytics/index.js'\nexport { buildSlugField, toSlug } from './modules/slug/index.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler, createManifestHandler } from './modules/seo/index.js'\n\nexport { getNotificationTexts, resolveFormMessage, NOTIFICATION_FALLBACK } from './modules/notifications/index.js'\nexport { buildSecurityHeaders } from './modules/security/index.js'\nexport { buildCsp } from './modules/security/index.js'\nexport type { BuildCspArgs } from './modules/security/index.js'\nexport { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js'\nexport { buildNoindexField } from './modules/seo/index.js'\nexport { rowLabel } from './modules/admin-ui/index.js'\nexport type { RowLabelProps } from './modules/admin-ui/index.js'\nexport { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'\nexport type {\n LinkAppearance,\n LinkValue,\n BuildLinkFieldOptions,\n BuildLinksFieldOptions,\n ResolveLinkHrefOptions,\n} from './modules/links/index.js'\nexport { buildSpeakableJsonLd } from './modules/seo/index.js'\nexport { buildSummaryField } from './modules/seo/index.js'\nexport { buildWebSiteJsonLd, buildBreadcrumbJsonLd, buildSiteNavigationJsonLd } from './modules/seo/index.js'\n// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.\nexport { buildLocalBusinessJsonLd, buildFaqJsonLd, buildServiceJsonLd } from './modules/seo/index.js'\nexport { buildArticleJsonLd } from './modules/seo/index.js'\nexport { buildLlmsTxt } from './modules/seo/index.js'\nexport { buildSitemapXml } from './modules/seo/index.js'\nexport { buildR2Storage } from './modules/storage/index.js'\nexport { normalizeFilename, normalizeFilenameHook, buildOptimizeUploadHook, buildOptimizeUploadField } from './modules/media/index.js'\nexport type { OptimizeUploadOptions } from './modules/media/index.js'\nexport { buildRevalidateHook, setPublishedAtHook, buildPreventDeleteSystemPage, buildValidateUniqueRole, trackSlugHistoryHook, buildCrossLocaleFieldSync } from './modules/hooks/index.js'\nexport { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js'\nexport type { A11yState } from './modules/accessibility/index.js'\nexport type { SecurityHeader, BuildSecurityHeadersArgs } from './modules/security/index.js'\nexport type { NotificationTexts, FormNotificationTexts } from './modules/notifications/index.js'\n"],"names":["ipalKit","buildLocalizedPath","getDefaultLocale","getLocaleCodes","getLocaleDefinition","getLocalizedSlugs","isValidLocale","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","switchLocalePath","ALL_SYSTEM_PAGE_ROLES","getSystemPagePath","adminOnly","adminOnlyField","adminOrEditor","adminOrEditorField","adminOrSelf","authenticated","hasMinimumRole","isAdmin","isEditor","requireRole","requireRoleField","ROLE_HIERARCHY","getGlobal","getSiteSettings","getSiteIntegrations","SITE_SETTINGS_SLUG","SITE_INTEGRATIONS_SLUG","composeTitle","buildHreflangAlternates","buildMetadata","readSiteMetaConfig","slugsAcrossLocales","createContentHelpers","resolveRoute","resolveRedirect","resolveNotFoundPage","blocksToMarkdown","createMarkdownRenderer","markdownResponse","prefersMarkdown","markdownHref","MARKDOWN_PREFIX","searchContent","createSearchRoute","archiveFieldName","getArchiveEntries","buildArchivePath","buildEntryPath","parsePageParam","lexicalToMarkdown","buildAutoFillMetaHook","injectAutoFillMeta","createMetadataGenerator","createPageMetadata","buildSitemapEntries","buildRobots","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","createProxy","DEFAULT_PROXY_MATCHER","resolveLocalized","CONSENT_CATEGORIES","DEFAULT_CONSENT","ACCEPT_ALL_CONSENT","REJECT_ALL_CONSENT","CONSENT_COOKIE","CONSENT_VERSION","CONSENT_MAX_AGE","serializeConsent","parseConsent","setDefaultConsent","updateConsent","getConsentTexts","panelSmtpAdapter","graphAdapter","mailAdapter","buildFormsPlugin","buildValidator","isEmail","required","email","minLength","maxLength","checked","pattern","custom","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","buildFormAnalyticsFields","createHealthRoute","createMcpRoute","assertEnv","ipalEnvRules","getAnalyticsConfig","buildSlugField","toSlug","createLlmsTxtRoute","createSitemapRouteHandler","createManifestHandler","getNotificationTexts","resolveFormMessage","NOTIFICATION_FALLBACK","buildSecurityHeaders","buildCsp","buildIconsMetadata","buildOrganizationJsonLd","validateFaviconField","buildNoindexField","rowLabel","buildLinkField","buildLinksField","resolveLinkHref","buildSpeakableJsonLd","buildSummaryField","buildWebSiteJsonLd","buildBreadcrumbJsonLd","buildSiteNavigationJsonLd","buildLocalBusinessJsonLd","buildFaqJsonLd","buildServiceJsonLd","buildArticleJsonLd","buildLlmsTxt","buildSitemapXml","buildR2Storage","normalizeFilename","normalizeFilenameHook","buildOptimizeUploadHook","buildOptimizeUploadField","buildRevalidateHook","setPublishedAtHook","buildPreventDeleteSystemPage","buildValidateUniqueRole","trackSlugHistoryHook","buildCrossLocaleFieldSync","A11Y_COOKIE","A11Y_DEFAULT","a11yAttributes","parseA11y","serializeA11y"],"mappings":"AAAA,SAASA,OAAO,QAAQ,cAAa;AAGrC,SACEC,kBAAkB,EAClBC,gBAAgB,EAChBC,cAAc,EACdC,mBAAmB,EACnBC,iBAAiB,EACjBC,aAAa,EACbC,kBAAkB,EAClBC,mBAAmB,EACnBC,eAAe,EACfC,gBAAgB,QACX,0BAAyB;AAEhC,SAASC,qBAAqB,EAAEC,iBAAiB,QAAQ,2BAA0B;AAEnF,SACEC,SAAS,EACTC,cAAc,EACdC,aAAa,EACbC,kBAAkB,EAClBC,WAAW,EACXC,aAAa,EACbC,cAAc,EACdC,OAAO,EACPC,QAAQ,EACRC,WAAW,EACXC,gBAAgB,EAChBC,cAAc,QACT,4BAA2B;AAElC,SACEC,SAAS,EACTC,eAAe,EACfC,mBAAmB,EACnBC,kBAAkB,EAClBC,sBAAsB,QACjB,6BAA4B;AAEnC,SACEC,YAAY,EACZC,uBAAuB,EACvBC,aAAa,EACbC,kBAAkB,EAClBC,kBAAkB,QACb,yBAAwB;AAG/B,SAASC,oBAAoB,QAAQ,8BAA6B;AAClE,SACEC,YAAY,EACZC,eAAe,EACfC,mBAAmB,EACnBC,gBAAgB,EAChBC,sBAAsB,EACtBC,gBAAgB,EAChBC,eAAe,EACfC,YAAY,EACZC,eAAe,EACfC,aAAa,EACbC,iBAAiB,EACjBC,gBAAgB,EAChBC,iBAAiB,EACjBC,gBAAgB,EAChBC,cAAc,EACdC,cAAc,QACT,6BAA4B;AAGnC,gEAAgE;AAChE,SAASC,iBAAiB,QAAQ,8BAA6B;AAE/D,SACEC,qBAA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AAwB;AAE7G,SAASC,oBAAoB,EAAEC,kBAAkB,EAAEC,qBAAqB,QAAQ,mCAAkC;AAClH,SAASC,oBAAoB,QAAQ,8BAA6B;AAClE,SAASC,QAAQ,QAAQ,8BAA6B;AAEtD,SAASC,kBAAkB,EAAEC,uBAAuB,EAAEC,oBAAoB,QAAQ,yBAAwB;AAC1G,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,QAAQ,QAAQ,8BAA6B;AAEtD,SAASC,cAAc,EAAEC,eAAe,EAAEC,eAAe,QAAQ,2BAA0B;AAQ3F,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,kBAAkB,EAAEC,qBAAqB,EAAEC,yBAAyB,QAAQ,yBAAwB;AAC7G,qFAAqF;AACrF,SAASC,wBAAwB,EAAEC,cAAc,EAAEC,kBAAkB,QAAQ,yBAAwB;AACrG,SAASC,kBAAkB,QAAQ,yBAAwB;AAC3D,SAASC,YAAY,QAAQ,yBAAwB;AACrD,SAASC,eAAe,QAAQ,yBAAwB;AACxD,SAASC,cAAc,QAAQ,6BAA4B;AAC3D,SAASC,iBAAiB,EAAEC,qBAAqB,EAAEC,uBAAuB,EAAEC,wBAAwB,QAAQ,2BAA0B;AAEtI,SAASC,mBAAmB,EAAEC,kBAAkB,EAAEC,4BAA4B,EAAEC,uBAAuB,EAAEC,oBAAoB,EAAEC,yBAAyB,QAAQ,2BAA0B;AAC1L,SAASC,WAAW,EAAEC,YAAY,EAAEC,cAAc,EAAEC,SAAS,EAAEC,aAAa,QAAQ,mCAAkC"} \ No newline at end of file diff --git a/dist/modules/admin-ui/RowLabelComponent.d.ts b/dist/modules/admin-ui/RowLabelComponent.d.ts new file mode 100644 index 0000000..0278733 --- /dev/null +++ b/dist/modules/admin-ui/RowLabelComponent.d.ts @@ -0,0 +1,12 @@ +export type RowLabelProps = { + /** Shown with the row number when every path is empty, e.g. "Button" → "Button 02". */ + fallback?: string; + /** Dot paths inside the row, tried in order — the first non-empty text wins. */ + fields?: string[]; +}; +/** + * Array row title in the admin panel: shows the row's own content ("Contact us", + * "Fast delivery") instead of "Item 01", so an editor finds the right row + * without expanding every one. Wire it with `rowLabel()`. + */ +export declare function RowLabel({ fallback, fields }: RowLabelProps): import("react/jsx-runtime").JSX.Element; diff --git a/dist/modules/admin-ui/RowLabelComponent.js b/dist/modules/admin-ui/RowLabelComponent.js new file mode 100644 index 0000000..8e6f943 --- /dev/null +++ b/dist/modules/admin-ui/RowLabelComponent.js @@ -0,0 +1,54 @@ +'use client'; +import { jsx as _jsx } from "react/jsx-runtime"; +import { useRowLabel } from '@payloadcms/ui'; +const at = (obj, path)=>path.split('.').reduce((o, k)=>o && typeof o === 'object' ? o[k] : undefined, obj); +const toText = (v)=>{ + if (typeof v === 'string') { + return v.trim(); + } + if (typeof v === 'number') { + return String(v); + } + // populated relationship / upload → its title, name, filename or alt + if (v && typeof v === 'object') { + for (const k of [ + 'title', + 'name', + 'label', + 'alt', + 'filename' + ]){ + const t = v[k]; + if (typeof t === 'string' && t.trim()) { + return t.trim(); + } + } + } + return ''; +}; +/** + * Array row title in the admin panel: shows the row's own content ("Contact us", + * "Fast delivery") instead of "Item 01", so an editor finds the right row + * without expanding every one. Wire it with `rowLabel()`. + */ export function RowLabel({ fallback = 'Item', fields = [ + 'heading', + 'title', + 'label', + 'link.label', + 'name' +] }) { + const { data, rowNumber } = useRowLabel(); + for (const f of fields){ + const text = toText(at(data, f)); + if (text) { + return /*#__PURE__*/ _jsx("span", { + children: text.length > 60 ? `${text.slice(0, 57)}…` : text + }); + } + } + return /*#__PURE__*/ _jsx("span", { + children: `${fallback} ${String((rowNumber ?? 0) + 1).padStart(2, '0')}` + }); +} + +//# sourceMappingURL=RowLabelComponent.js.map \ No newline at end of file diff --git a/dist/modules/admin-ui/RowLabelComponent.js.map b/dist/modules/admin-ui/RowLabelComponent.js.map new file mode 100644 index 0000000..5fcfa9d --- /dev/null +++ b/dist/modules/admin-ui/RowLabelComponent.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/admin-ui/RowLabelComponent.tsx"],"sourcesContent":["'use client'\nimport { useRowLabel } from '@payloadcms/ui'\n\nexport type RowLabelProps = {\n /** Shown with the row number when every path is empty, e.g. \"Button\" → \"Button 02\". */\n fallback?: string\n /** Dot paths inside the row, tried in order — the first non-empty text wins. */\n fields?: string[]\n}\n\nconst at = (obj: unknown, path: string): unknown =>\n path.split('.').reduce((o, k) => (o && typeof o === 'object' ? (o as Record)[k] : undefined), obj)\n\nconst toText = (v: unknown): string => {\n if (typeof v === 'string') {return v.trim()}\n if (typeof v === 'number') {return String(v)}\n // populated relationship / upload → its title, name, filename or alt\n if (v && typeof v === 'object') {\n for (const k of ['title', 'name', 'label', 'alt', 'filename']) {\n const t = (v as Record)[k]\n if (typeof t === 'string' && t.trim()) {return t.trim()}\n }\n }\n return ''\n}\n\n/**\n * Array row title in the admin panel: shows the row's own content (\"Contact us\",\n * \"Fast delivery\") instead of \"Item 01\", so an editor finds the right row\n * without expanding every one. Wire it with `rowLabel()`.\n */\nexport function RowLabel({ fallback = 'Item', fields = ['heading', 'title', 'label', 'link.label', 'name'] }: RowLabelProps) {\n const { data, rowNumber } = useRowLabel>()\n for (const f of fields) {\n const text = toText(at(data, f))\n if (text) {return {text.length > 60 ? `${text.slice(0, 57)}…` : text}}\n }\n return {`${fallback} ${String((rowNumber ?? 0) + 1).padStart(2, '0')}`}\n}\n"],"names":["useRowLabel","at","obj","path","split","reduce","o","k","undefined","toText","v","trim","String","t","RowLabel","fallback","fields","data","rowNumber","f","text","span","length","slice","padStart"],"mappings":"AAAA;;AACA,SAASA,WAAW,QAAQ,iBAAgB;AAS5C,MAAMC,KAAK,CAACC,KAAcC,OACxBA,KAAKC,KAAK,CAAC,KAAKC,MAAM,CAAU,CAACC,GAAGC,IAAOD,KAAK,OAAOA,MAAM,WAAW,AAACA,CAA6B,CAACC,EAAE,GAAGC,WAAYN;AAE1H,MAAMO,SAAS,CAACC;IACd,IAAI,OAAOA,MAAM,UAAU;QAAC,OAAOA,EAAEC,IAAI;IAAE;IAC3C,IAAI,OAAOD,MAAM,UAAU;QAAC,OAAOE,OAAOF;IAAE;IAC5C,qEAAqE;IACrE,IAAIA,KAAK,OAAOA,MAAM,UAAU;QAC9B,KAAK,MAAMH,KAAK;YAAC;YAAS;YAAQ;YAAS;YAAO;SAAW,CAAE;YAC7D,MAAMM,IAAI,AAACH,CAA6B,CAACH,EAAE;YAC3C,IAAI,OAAOM,MAAM,YAAYA,EAAEF,IAAI,IAAI;gBAAC,OAAOE,EAAEF,IAAI;YAAE;QACzD;IACF;IACA,OAAO;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASG,SAAS,EAAEC,WAAW,MAAM,EAAEC,SAAS;IAAC;IAAW;IAAS;IAAS;IAAc;CAAO,EAAiB;IACzH,MAAM,EAAEC,IAAI,EAAEC,SAAS,EAAE,GAAGlB;IAC5B,KAAK,MAAMmB,KAAKH,OAAQ;QACtB,MAAMI,OAAOX,OAAOR,GAAGgB,MAAME;QAC7B,IAAIC,MAAM;YAAC,qBAAO,KAACC;0BAAMD,KAAKE,MAAM,GAAG,KAAK,GAAGF,KAAKG,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,GAAGH;;QAAY;IACpF;IACA,qBAAO,KAACC;kBAAM,GAAGN,SAAS,CAAC,EAAEH,OAAO,AAACM,CAAAA,aAAa,CAAA,IAAK,GAAGM,QAAQ,CAAC,GAAG,MAAM;;AAC9E"} \ No newline at end of file diff --git a/dist/modules/admin-ui/index.d.ts b/dist/modules/admin-ui/index.d.ts new file mode 100644 index 0000000..687c772 --- /dev/null +++ b/dist/modules/admin-ui/index.d.ts @@ -0,0 +1,2 @@ +export { rowLabel } from './rowLabel.js'; +export type { RowLabelProps } from './RowLabelComponent.js'; diff --git a/dist/modules/admin-ui/index.js b/dist/modules/admin-ui/index.js new file mode 100644 index 0000000..cca268a --- /dev/null +++ b/dist/modules/admin-ui/index.js @@ -0,0 +1,3 @@ +export { rowLabel } from './rowLabel.js'; + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/modules/admin-ui/index.js.map b/dist/modules/admin-ui/index.js.map new file mode 100644 index 0000000..7b3c0b1 --- /dev/null +++ b/dist/modules/admin-ui/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/admin-ui/index.ts"],"sourcesContent":["export { rowLabel } from './rowLabel.js'\nexport type { RowLabelProps } from './RowLabelComponent.js'\n"],"names":["rowLabel"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAe"} \ No newline at end of file diff --git a/dist/modules/admin-ui/rowLabel.d.ts b/dist/modules/admin-ui/rowLabel.d.ts new file mode 100644 index 0000000..f927880 --- /dev/null +++ b/dist/modules/admin-ui/rowLabel.d.ts @@ -0,0 +1,16 @@ +import type { RowLabelProps } from './RowLabelComponent.js'; +/** + * Readable array rows in the panel. Spread into an array field's `admin.components`: + * + * { name: 'items', type: 'array', labels: { singular: 'Feature', plural: 'Features' }, + * admin: { initCollapsed: true, components: rowLabel(['heading'], 'Feature') }, fields: [...] } + * + * Rows then read "Fast delivery", "24/7 support"… instead of "Feature 01, Feature 02". + * After adding it to a project: `pnpm payload generate:importmap`. + */ +export declare function rowLabel(fields: string | string[], fallback?: string): { + RowLabel: { + path: string; + clientProps: RowLabelProps; + }; +}; diff --git a/dist/modules/admin-ui/rowLabel.js b/dist/modules/admin-ui/rowLabel.js new file mode 100644 index 0000000..b516a08 --- /dev/null +++ b/dist/modules/admin-ui/rowLabel.js @@ -0,0 +1,24 @@ +/** + * Readable array rows in the panel. Spread into an array field's `admin.components`: + * + * { name: 'items', type: 'array', labels: { singular: 'Feature', plural: 'Features' }, + * admin: { initCollapsed: true, components: rowLabel(['heading'], 'Feature') }, fields: [...] } + * + * Rows then read "Fast delivery", "24/7 support"… instead of "Feature 01, Feature 02". + * After adding it to a project: `pnpm payload generate:importmap`. + */ export function rowLabel(fields, fallback = 'Item') { + const clientProps = { + fields: Array.isArray(fields) ? fields : [ + fields + ], + fallback + }; + return { + RowLabel: { + path: '@intecion/ipal-kit/admin#RowLabel', + clientProps + } + }; +} + +//# sourceMappingURL=rowLabel.js.map \ No newline at end of file diff --git a/dist/modules/admin-ui/rowLabel.js.map b/dist/modules/admin-ui/rowLabel.js.map new file mode 100644 index 0000000..24b328d --- /dev/null +++ b/dist/modules/admin-ui/rowLabel.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/admin-ui/rowLabel.ts"],"sourcesContent":["import type { RowLabelProps } from './RowLabelComponent.js'\n\n/**\n * Readable array rows in the panel. Spread into an array field's `admin.components`:\n *\n * { name: 'items', type: 'array', labels: { singular: 'Feature', plural: 'Features' },\n * admin: { initCollapsed: true, components: rowLabel(['heading'], 'Feature') }, fields: [...] }\n *\n * Rows then read \"Fast delivery\", \"24/7 support\"… instead of \"Feature 01, Feature 02\".\n * After adding it to a project: `pnpm payload generate:importmap`.\n */\nexport function rowLabel(fields: string | string[], fallback = 'Item') {\n const clientProps: RowLabelProps = { fields: Array.isArray(fields) ? fields : [fields], fallback }\n return { RowLabel: { path: '@intecion/ipal-kit/admin#RowLabel', clientProps } }\n}\n"],"names":["rowLabel","fields","fallback","clientProps","Array","isArray","RowLabel","path"],"mappings":"AAEA;;;;;;;;CAQC,GACD,OAAO,SAASA,SAASC,MAAyB,EAAEC,WAAW,MAAM;IACnE,MAAMC,cAA6B;QAAEF,QAAQG,MAAMC,OAAO,CAACJ,UAAUA,SAAS;YAACA;SAAO;QAAEC;IAAS;IACjG,OAAO;QAAEI,UAAU;YAAEC,MAAM;YAAqCJ;QAAY;IAAE;AAChF"} \ No newline at end of file diff --git a/dist/modules/consent/CookieBanner.js b/dist/modules/consent/CookieBanner.js index 57e59bb..7388ce2 100644 --- a/dist/modules/consent/CookieBanner.js +++ b/dist/modules/consent/CookieBanner.js @@ -68,7 +68,7 @@ export function CookieBanner({ classNames } = {}) { const primaryClass = classNames?.primaryButton ?? defaults.primaryButton; const secondaryClass = classNames?.secondaryButton ?? defaults.secondaryButton; return /*#__PURE__*/ _jsx("div", { - "aria-label": "Cookie consent", + "aria-label": texts.settingsTitle, className: rootClass, "data-ipal": "banner", role: "dialog", @@ -107,16 +107,19 @@ export function CookieBanner({ classNames } = {}) { children: [ /*#__PURE__*/ _jsx("button", { className: secondaryClass, + "data-ipal": "settings", onClick: ()=>setShowSettings(true), children: texts.buttons.settings }), /*#__PURE__*/ _jsx("button", { className: secondaryClass, + "data-ipal": "reject", onClick: rejectAll, children: texts.buttons.reject }), /*#__PURE__*/ _jsx("button", { className: primaryClass, + "data-ipal": "accept", onClick: acceptAll, children: texts.buttons.acceptAll }) @@ -168,11 +171,13 @@ export function CookieBanner({ classNames } = {}) { children: [ /*#__PURE__*/ _jsx("button", { className: secondaryClass, + "data-ipal": "back", onClick: ()=>setShowSettings(false), children: texts.buttons.back }), /*#__PURE__*/ _jsx("button", { className: primaryClass, + "data-ipal": "save", onClick: ()=>savePreferences(choices), children: texts.buttons.save }) diff --git a/dist/modules/consent/CookieBanner.js.map b/dist/modules/consent/CookieBanner.js.map index 83f0e62..af3a24b 100644 --- a/dist/modules/consent/CookieBanner.js.map +++ b/dist/modules/consent/CookieBanner.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/consent/CookieBanner.tsx"],"sourcesContent":["'use client'\nimport { Cookie } from 'lucide-react'\nimport { useEffect, useState } from 'react'\n\nimport { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'\nimport { useConsentContext } from './ConsentContext.js'\nimport { useIsMounted } from './useIsMounted.js'\n\n/**\n * Optional class overrides — for when tokens aren't enough, e.g. turning the\n * bottom bar into a centred modal. Replaces the slot's classes outright.\n */\nexport type CookieBannerClassNames = {\n primaryButton?: string\n root?: string\n secondaryButton?: string\n}\n\n/**\n * Colours and radius come from CSS custom properties with built-in fallbacks,\n * so the banner looks right with no setup, and re-skinning per client means\n * declaring a few variables — no imports, no props, no specificity fights:\n *\n * ```css\n * :root {\n * --ipal-primary: #16a34a;\n * --ipal-radius: 1rem;\n * }\n * ```\n *\n * Available: --ipal-surface, --ipal-border, --ipal-text, --ipal-text-strong,\n * --ipal-text-muted, --ipal-primary, --ipal-primary-hover, --ipal-primary-text,\n * --ipal-hover, --ipal-radius. Each has a `-dark` counterpart used under\n * Tailwind's `dark:` variant (e.g. --ipal-surface-dark).\n *\n * Layout stays in Tailwind: spacing and flow aren't things a brand changes, and\n * exposing them as tokens would mean re-inventing CSS one variable at a time.\n */\nconst surface = 'bg-[var(--ipal-surface,#fff)] dark:bg-[var(--ipal-surface-dark,#171717)]'\nconst border = 'border-[var(--ipal-border,#e5e5e5)] dark:border-[var(--ipal-border-dark,#262626)]'\nconst radius = 'rounded-[var(--ipal-radius,0.375rem)]'\nconst accent = 'text-[var(--ipal-primary,#2563eb)]'\n\nconst defaults = {\n primaryButton: `${radius} px-3 py-1.5 text-sm font-medium bg-[var(--ipal-primary,#2563eb)] text-[var(--ipal-primary-text,#fff)] hover:bg-[var(--ipal-primary-hover,#1d4ed8)]`,\n root: `fixed inset-x-0 bottom-0 z-50 border-t p-4 shadow-lg ${surface} ${border}`,\n secondaryButton: `${radius} px-3 py-1.5 text-sm font-medium text-[var(--ipal-text,#404040)] hover:bg-[var(--ipal-hover,#f5f5f5)] dark:text-[var(--ipal-text-dark,#e5e5e5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`,\n}\n\nconst bodyText = 'text-[var(--ipal-text,#404040)] dark:text-[var(--ipal-text-dark,#d4d4d4)]'\nconst strongText =\n 'text-[var(--ipal-text-strong,#171717)] dark:text-[var(--ipal-text-strong-dark,#f5f5f5)]'\nconst mutedText =\n 'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'\n\nexport function CookieBanner({ classNames }: { classNames?: CookieBannerClassNames } = {}) {\n const isMounted = useIsMounted()\n const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()\n const [showSettings, setShowSettings] = useState(false)\n const [choices, setChoices] = useState>(state)\n\n useEffect(() => {\n setChoices(state)\n }, [state])\n\n // Render nothing until mounted — avoids the React 19 hydration mismatch that\n // projects used to work around with a setTimeout ConsentWrapper. No wrapper\n // needed now.\n if (!isMounted) {return null}\n if (decided) {return null}\n\n const toggle = (cat: ConsentCategory) => {\n if (cat === 'necessary') {return}\n setChoices((prev) => ({ ...prev, [cat]: !prev[cat] }))\n }\n\n const rootClass = classNames?.root ?? defaults.root\n const primaryClass = classNames?.primaryButton ?? defaults.primaryButton\n const secondaryClass = classNames?.secondaryButton ?? defaults.secondaryButton\n\n return (\n
\n
\n {!showSettings ? (\n
\n
\n \n

\n {texts.message}\n {texts.privacyLink && (\n <>\n {' '}\n \n {texts.privacyLink.label}\n \n \n )}\n

\n
\n
\n \n \n \n
\n
\n ) : (\n
\n

\n \n {texts.settingsTitle}\n

\n
    \n {CONSENT_CATEGORIES.map((cat) => (\n
  • \n
    \n

    \n {texts.categories[cat].title}\n

    \n

    {texts.categories[cat].description}

    \n
    \n toggle(cat)}\n type=\"checkbox\"\n />\n
  • \n ))}\n
\n
\n \n \n
\n
\n )}\n
\n
\n )\n}\n"],"names":["Cookie","useEffect","useState","CONSENT_CATEGORIES","useConsentContext","useIsMounted","surface","border","radius","accent","defaults","primaryButton","root","secondaryButton","bodyText","strongText","mutedText","CookieBanner","classNames","isMounted","acceptAll","decided","rejectAll","savePreferences","state","texts","showSettings","setShowSettings","choices","setChoices","toggle","cat","prev","rootClass","primaryClass","secondaryClass","div","aria-label","className","data-ipal","role","aria-hidden","p","message","privacyLink","a","href","label","button","onClick","buttons","settings","reject","h2","settingsTitle","ul","map","li","categories","title","description","input","checked","disabled","onChange","type","back","save"],"mappings":"AAAA;;AACA,SAASA,MAAM,QAAQ,eAAc;AACrC,SAASC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAE3C,SAASC,kBAAkB,QAA8B,kBAAiB;AAC1E,SAASC,iBAAiB,QAAQ,sBA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,WAAW;0DAAGS,MAAMiC,UAAU,CAAC3B,IAAI,CAAC6B,WAAW;;;;kDAE1E,KAACC;wCACCC,SAAS/B,QAAQ,cAAc,OAAOH,OAAO,CAACG,IAAI;wCAClDO,WAAU;wCACVyB,UAAUhC,QAAQ;wCAClBiC,UAAU,IAAMlC,OAAOC;wCACvBkC,MAAK;;;+BAZmDlC;;kCAiBhE,MAACK;wBAAIE,WAAU;;0CACb,KAACU;gCAAOV,WAAWH;gCAAgBc,SAAS,IAAMtB,gBAAgB;0CAC/DF,MAAMyB,OAAO,CAACgB,IAAI;;0CAErB,KAAClB;gCAAOV,WAAWJ;gCAAce,SAAS,IAAM1B,gBAAgBK;0CAC7DH,MAAMyB,OAAO,CAACiB,IAAI;;;;;;;;AAQnC"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/consent/CookieBanner.tsx"],"sourcesContent":["'use client'\nimport { Cookie } from 'lucide-react'\nimport { useEffect, useState } from 'react'\n\nimport { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'\nimport { useConsentContext } from './ConsentContext.js'\nimport { useIsMounted } from './useIsMounted.js'\n\n/**\n * Optional class overrides — for when tokens aren't enough, e.g. turning the\n * bottom bar into a centred modal. Replaces the slot's classes outright.\n */\nexport type CookieBannerClassNames = {\n primaryButton?: string\n root?: string\n secondaryButton?: string\n}\n\n/**\n * Colours and radius come from CSS custom properties with built-in fallbacks,\n * so the banner looks right with no setup, and re-skinning per client means\n * declaring a few variables — no imports, no props, no specificity fights:\n *\n * ```css\n * :root {\n * --ipal-primary: #16a34a;\n * --ipal-radius: 1rem;\n * }\n * ```\n *\n * Available: --ipal-surface, --ipal-border, --ipal-text, --ipal-text-strong,\n * --ipal-text-muted, --ipal-primary, --ipal-primary-hover, --ipal-primary-text,\n * --ipal-hover, --ipal-radius. Each has a `-dark` counterpart used under\n * Tailwind's `dark:` variant (e.g. --ipal-surface-dark).\n *\n * Layout stays in Tailwind: spacing and flow aren't things a brand changes, and\n * exposing them as tokens would mean re-inventing CSS one variable at a time.\n */\nconst surface = 'bg-[var(--ipal-surface,#fff)] dark:bg-[var(--ipal-surface-dark,#171717)]'\nconst border = 'border-[var(--ipal-border,#e5e5e5)] dark:border-[var(--ipal-border-dark,#262626)]'\nconst radius = 'rounded-[var(--ipal-radius,0.375rem)]'\nconst accent = 'text-[var(--ipal-primary,#2563eb)]'\n\nconst defaults = {\n primaryButton: `${radius} px-3 py-1.5 text-sm font-medium bg-[var(--ipal-primary,#2563eb)] text-[var(--ipal-primary-text,#fff)] hover:bg-[var(--ipal-primary-hover,#1d4ed8)]`,\n root: `fixed inset-x-0 bottom-0 z-50 border-t p-4 shadow-lg ${surface} ${border}`,\n secondaryButton: `${radius} px-3 py-1.5 text-sm font-medium text-[var(--ipal-text,#404040)] hover:bg-[var(--ipal-hover,#f5f5f5)] dark:text-[var(--ipal-text-dark,#e5e5e5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`,\n}\n\nconst bodyText = 'text-[var(--ipal-text,#404040)] dark:text-[var(--ipal-text-dark,#d4d4d4)]'\nconst strongText =\n 'text-[var(--ipal-text-strong,#171717)] dark:text-[var(--ipal-text-strong-dark,#f5f5f5)]'\nconst mutedText =\n 'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'\n\nexport function CookieBanner({ classNames }: { classNames?: CookieBannerClassNames } = {}) {\n const isMounted = useIsMounted()\n const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()\n const [showSettings, setShowSettings] = useState(false)\n const [choices, setChoices] = useState>(state)\n\n useEffect(() => {\n setChoices(state)\n }, [state])\n\n // Render nothing until mounted — avoids the React 19 hydration mismatch that\n // projects used to work around with a setTimeout ConsentWrapper. No wrapper\n // needed now.\n if (!isMounted) {return null}\n if (decided) {return null}\n\n const toggle = (cat: ConsentCategory) => {\n if (cat === 'necessary') {return}\n setChoices((prev) => ({ ...prev, [cat]: !prev[cat] }))\n }\n\n const rootClass = classNames?.root ?? defaults.root\n const primaryClass = classNames?.primaryButton ?? defaults.primaryButton\n const secondaryClass = classNames?.secondaryButton ?? defaults.secondaryButton\n\n return (\n
\n
\n {!showSettings ? (\n
\n
\n \n

\n {texts.message}\n {texts.privacyLink && (\n <>\n {' '}\n \n {texts.privacyLink.label}\n \n \n )}\n

\n
\n
\n \n \n \n
\n
\n ) : (\n
\n

\n \n {texts.settingsTitle}\n

\n
    \n {CONSENT_CATEGORIES.map((cat) => (\n
  • \n
    \n

    \n {texts.categories[cat].title}\n

    \n

    {texts.categories[cat].description}

    \n
    \n toggle(cat)}\n type=\"checkbox\"\n />\n
  • \n ))}\n
\n
\n \n \n
\n
\n )}\n
\n
\n )\n}\n"],"names":["Cookie","useEffect","useState","CONSENT_CATEGORIES","useConsentContext","useIsMounted","surface","border","radius","accent","defaults","primaryButton","root","secondaryButton","bodyText","strongText","mutedText","CookieBanner","classNames","isMounted","acceptAll","decided","rejectAll","savePreferences","state","texts","showSettings","setShowSettings","choices","setChoices","toggle","cat","prev","rootClass","primaryClass","secondaryClass","div","aria-label","settingsTitle","className","data-ipal","role","aria-hidden","p","message","privacyLink","a","href","label","button","onClick","buttons","settings","reject","h2","ul","map","li","categories","title","description","input","checked","disabled","onChange","type","back","save"],"mappings":"AAAA;;AACA,SAASA,MAAM,QAAQ,eAAc;AACrC,SAASC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAE3C,SAASC,kBAAkB,QAA8B,kBAAiB;AAC1E,SAASC,iBAAiB,QAAQ,sBAAqB;AACvD,SAASC,YAAY,QAAQ,oBAAmB;AAYhD;;;;;;;;;;;;;;;;;;;CAmBC,GACD,MAAMC,UAAU;AAChB,MAAMC,SAAS;AACf,MAAMC,SAAS;AACf,MAAMC,SAAS;AAEf,MAAMC,WAAW;IACfC,eAAe,GAAGH,OAAO,mJAAmJ,CAAC;IAC7KI,MAAM,CAAC,qDAAqD,EAAEN,QAAQ,CAAC,EAAEC,QAAQ;IACjFM,iBAAiB,GAAGL,OAAO,8L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;wBAAIG,WAAU;;0CACb,KAACU;gCAAOV,WAAWJ;gCAAgBK,aAAU;gCAAOU,SAAS,IAAMvB,gBAAgB;0CAChFF,MAAM0B,OAAO,CAACe,IAAI;;0CAErB,KAACjB;gCAAOV,WAAWL;gCAAcM,aAAU;gCAAOU,SAAS,IAAM3B,gBAAgBK;0CAC9EH,MAAM0B,OAAO,CAACgB,IAAI;;;;;;;;AAQnC"} \ No newline at end of file diff --git a/dist/modules/consent/CookieButton.js b/dist/modules/consent/CookieButton.js index 36b2d92..83a8e10 100644 --- a/dist/modules/consent/CookieButton.js +++ b/dist/modules/consent/CookieButton.js @@ -14,7 +14,7 @@ import { useIsMounted } from './useIsMounted.js'; * replace the styling outright. */ export function CookieButton({ className } = {}) { const isMounted = useIsMounted(); - const { decided, reopen } = useConsentContext(); + const { decided, reopen, texts } = useConsentContext(); // Render nothing until mounted — prevents hydration mismatch (no project // ConsentWrapper workaround needed). if (!isMounted) { @@ -25,7 +25,8 @@ import { useIsMounted } from './useIsMounted.js'; } const cls = className ?? 'fixed bottom-4 left-4 z-40 flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-colors ' + 'bg-[var(--ipal-surface,#fff)] border-[var(--ipal-border,#e5e5e5)] hover:bg-[var(--ipal-hover,#f5f5f5)] ' + 'dark:bg-[var(--ipal-surface-dark,#171717)] dark:border-[var(--ipal-border-dark,#262626)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]'; return /*#__PURE__*/ _jsx("button", { - "aria-label": "Cookie settings", + // a11y label per locale: the panel's "settings title" (Cookie Settings global) + "aria-label": texts.settingsTitle, className: cls, "data-ipal": "cookie-button", onClick: reopen, diff --git a/dist/modules/consent/CookieButton.js.map b/dist/modules/consent/CookieButton.js.map index 4b60a1e..d8409c5 100644 --- a/dist/modules/consent/CookieButton.js.map +++ b/dist/modules/consent/CookieButton.js.map @@ -1 +1 @@ -{"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 \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"} \ No newline at end of file +{"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, texts } = 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 \n \n \n )\n}\n"],"names":["Cookie","useConsentContext","useIsMounted","CookieButton","className","isMounted","decided","reopen","texts","cls","button","aria-label","settingsTitle","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,EAAEC,KAAK,EAAE,GAAGP;IAEnC,yEAAyE;IACzE,qCAAqC;IACrC,IAAI,CAACI,WAAW;QAAC,OAAO;IAAI;IAC5B,IAAI,CAACC,SAAS;QAAC,OAAO;IAAI;IAE1B,MAAMG,MACJL,aACA,2HACE,4GACA;IAEJ,qBACE,KAACM;QACC,+EAA+E;QAC/EC,cAAYH,MAAMI,aAAa;QAC/BR,WAAWK;QACXI,aAAU;QACVC,SAASP;kBAET,cAAA,KAACP;YACCe,eAAY;YACZX,WAAU;;;AAIlB"} \ No newline at end of file diff --git a/dist/modules/forms/submitForm.d.ts b/dist/modules/forms/submitForm.d.ts index 62b494f..8a7c99b 100644 --- a/dist/modules/forms/submitForm.d.ts +++ b/dist/modules/forms/submitForm.d.ts @@ -76,7 +76,7 @@ export type SubmitFormResult = { * * Emails aren't sent here. The form-builder sends whatever an editor configured * under the form's "Emails" tab (form-submissions hook → payload.sendEmail), - * which goes out over panelSmtpAdapter. Storing the submission is enough. + * which goes out over the configured email adapter (mailAdapter). Storing the submission is enough. * * server-only: touches the Turnstile secret. */ diff --git a/dist/modules/forms/submitForm.js b/dist/modules/forms/submitForm.js index 8449018..d39f2ed 100644 --- a/dist/modules/forms/submitForm.js +++ b/dist/modules/forms/submitForm.js @@ -11,7 +11,7 @@ import { validateSubmission } from './validateSubmission.js'; * * Emails aren't sent here. The form-builder sends whatever an editor configured * under the form's "Emails" tab (form-submissions hook → payload.sendEmail), - * which goes out over panelSmtpAdapter. Storing the submission is enough. + * which goes out over the configured email adapter (mailAdapter). Storing the submission is enough. * * server-only: touches the Turnstile secret. */ export async function submitForm({ consentFieldName, data, formId, ip, maxPerMinute = 5, payload, turnstileToken }) { diff --git a/dist/modules/forms/submitForm.js.map b/dist/modules/forms/submitForm.js.map index 597fd64..198c712 100644 --- a/dist/modules/forms/submitForm.js.map +++ b/dist/modules/forms/submitForm.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/forms/submitForm.ts"],"sourcesContent":["import 'server-only'\n\nimport type { BasePayload } from 'payload'\n\nimport { verifyTurnstile } from '../turnstile/index.js'\nimport { checkRateLimit } from './rateLimit.js'\nimport { validateSubmission } from './validateSubmission.js'\n\nexport type SubmitFormArgs = {\n /**\n * Name of the GDPR consent checkbox. A field with this name must be checked\n * for the submission to succeed (enforced server-side). Defaults to 'consent'.\n */\n consentFieldName?: string\n /** Submitted field data — shape matches the form's fields. */\n data: Record\n /** Form-builder form ID this submission belongs to. */\n formId: string\n /** Client IP — used for Turnstile and rate limiting. */\n ip?: string\n /**\n * Rate limit: max submissions per IP per minute. Defaults to 5.\n * Set to 0 to disable (e.g. when a real limiter sits in front).\n */\n maxPerMinute?: number\n payload: BasePayload\n /** Turnstile token; when present it is verified, when absent it is skipped. */\n turnstileToken?: string\n}\n\n/**\n * Why a submission failed — a code, never a user-facing string.\n *\n * The plugin knows what went wrong; it deliberately doesn't decide how to say\n * it. The frontend maps these to its own copy, in its own language, and renders\n * whatever component fits — a field error, a toast, a full message. The plugin\n * has no business choosing the wording or the locale.\n *\n * - `rate_limited` — too many submissions from this IP\n * - `turnstile` — bot check failed\n * - `validation` — a field is missing/too long, or unknown keys were sent;\n * `field` and `kind` narrow it down when a specific field is\n * at fault (absent for whole-payload problems like unknown keys)\n * - `not_found` — no form with this id\n * - `consent` — a required GDPR consent checkbox was left unchecked\n * - `error` — persistence failed unexpectedly\n */\nexport type SubmitFailure =\n | {\n /** The offending field's name, when one field is at fault. */\n field?: string\n /** What was wrong with it. */\n kind?: 'required' | 'too_long' | 'unknown_fields'\n reason: 'validation'\n success: false\n }\n | {\n field?: string\n /** A GDPR consent field existed on the form but wasn't checked. */\n reason: 'consent'\n success: false\n }\n | { reason: 'error'; success: false }\n | { reason: 'not_found'; success: false }\n | { reason: 'rate_limited'; success: false }\n | { reason: 'turnstile'; success: false }\n\nexport type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure\n\n/**\n * Handles a form submission end to end: rate limit, verify Turnstile, validate\n * against the form's own schema, then store.\n *\n * The order is cost-ascending on purpose — the cheapest checks reject first, so\n * a flood never reaches Turnstile's network call or the database.\n *\n * Emails aren't sent here. The form-builder sends whatever an editor configured\n * under the form's \"Emails\" tab (form-submissions hook → payload.sendEmail),\n * which goes out over panelSmtpAdapter. Storing the submission is enough.\n *\n * server-only: touches the Turnstile secret.\n */\nexport async function submitForm({\n consentFieldName,\n data,\n formId,\n ip,\n maxPerMinute = 5,\n payload,\n turnstileToken,\n}: SubmitFormArgs): Promise {\n // 1. Rate limit — cheapest gate, drops a flood before any real work.\n if (maxPerMinute > 0 && ip) {\n if (!checkRateLimit({ key: ip, max: maxPerMinute })) {\n return { reason: 'rate_limited', success: false }\n }\n }\n\n // 2. Turnstile — verify when a token is supplied; reject on failure.\n if (turnstileToken !== undefined) {\n const ok = await verifyTurnstile({ ip, payload, token: turnstileToken })\n if (!ok) {\n return { reason: 'turnstile', success: false }\n }\n }\n\n // 3. Validate against the form's schema. A public endpoint can't trust the\n // shape of `data` — drop unknown keys, enforce required, cap length.\n const validation = await validateSubmission(payload, formId, data, consentFieldName)\n if (!validation.ok) {\n if (validation.reason === 'not_found') {\n return { reason: 'not_found', success: false }\n }\n if (validation.reason === 'consent') {\n return { field: validation.field, reason: 'consent', success: false }\n }\n return {\n reason: 'validation',\n success: false,\n ...(validation.field ? { field: validation.field } : {}),\n ...(validation.kind ? { kind: validation.kind } : {}),\n }\n }\n\n // 4. Persist (form-builder shape: submissionData array). Triggers the email\n // hook. Only validated, known fields are stored.\n try {\n const submission = await payload.create({\n collection: 'form-submissions',\n data: {\n form: formId,\n submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({\n field,\n value: value == null ? '' : String(value),\n })),\n } as never,\n })\n return { submissionId: submission.id, success: true }\n } catch (err) {\n payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)\n return { reason: 'error', success: false }\n }\n}\n"],"names":["verifyTurnstile","checkRateLimit","validateSubmission","submitForm","consentFieldName","data","formId","ip","maxPerMinute","payload","turnstileToken","key","max","reason","success","undefined","ok","token","validation","field","kind","submission","create","collection","form","submissionData","Object","entries","cleaned","map","value","String","submissionId","id","err","logger","error","message"],"mappings":"AAAA,OAAO,cAAa;AAIpB,SAASA,eAAe,QAAQ,wBAAuB;AACvD,SAASC,cAAc,QAAQ,iBAAgB;AAC/C,SAASC,kBAAkB,QAAQ,0BAAyB;AA+D5D;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeC,WAAW,EAC/BC,gBAAgB,EAChBC,IAAI,EACJC,MAAM,EACNC,EAAE,EACFC,eAAe,CAAC,EAChBC,OAAO,EACPC,cAAc,EACC;IACf,qEAAqE;IACrE,IAAIF,eAAe,KAAKD,IAAI;QAC1B,IAAI,CAACN,eAAe;YAAEU,KAAKJ;YAAIK,KAAKJ;QAAa,IAAI;YACnD,OAAO;gBAAEK,QAAQ;gBAAgBC,SAAS;YAAM;QAClD;IACF;IAEA,qEAAqE;IACrE,IAAIJ,mBAAmBK,WAAW;QAChC,MAAMC,KAAK,MAAMhB,gBAAgB;YAAEO;YAAIE;YAASQ,OAAOP;QAAe;QACtE,IAAI,CAACM,IAAI;YACP,OAAO;gBAAEH,QAAQ;gBAAaC,SAAS;YAAM;QAC/C;IACF;IAEA,2EAA2E;IAC3E,wEAAwE;IACxE,MAAMI,aAAa,MAAMhB,mBAAmBO,SAASH,QAAQD,MAAMD;IACnE,IAAI,CAACc,WAAWF,EAAE,EAAE;QAClB,IAAIE,WAAWL,MAAM,KAAK,aAAa;YACrC,OAAO;gBAAEA,QAAQ;gBAAaC,SAAS;YAAM;QAC/C;QACA,IAAII,WAAWL,MAAM,KAAK,WAAW;YACnC,OAAO;gBAAEM,OAAOD,WAAWC,KAAK;gBAAEN,QAAQ;gBAAWC,SAAS;YAAM;QACtE;QACA,OAAO;YACLD,QAAQ;YACRC,SAAS;YACT,GAAII,WAAWC,KAAK,GAAG;gBAAEA,OAAOD,WAAWC,KAAK;YAAC,IAAI,CAAC,CAAC;YACvD,GAAID,WAAWE,IAAI,GAAG;gBAAEA,MAAMF,WAAWE,IAAI;YAAC,IAAI,CAAC,CAAC;QACtD;IACF;IAEA,4EAA4E;IAC5E,oDAAoD;IACpD,IAAI;QACF,MAAMC,aAAa,MAAMZ,QAAQa,MAAM,CAAC;YACtCC,YAAY;YACZlB,MAAM;gBACJmB,MAAMlB;gBACNmB,gBAAgBC,OAAOC,OAAO,CAACT,WAAWU,OAAO,EAAEC,GAAG,CAAC,CAAC,CAACV,OAAOW,MAAM,GAAM,CAAA;wBAC1EX;wBACAW,OAAOA,SAAS,OAAO,KAAKC,OAAOD;oBACrC,CAAA;YACF;QACF;QACA,OAAO;YAAEE,cAAcX,WAAWY,EAAE;YAAEnB,SAAS;QAAK;IACtD,EAAE,OAAOoB,KAAK;QACZzB,QAAQ0B,MAAM,CAACC,KAAK,CAAC,CAAC,+BAA+B,EAAE,AAACF,IAAcG,OAAO,EAAE;QAC/E,OAAO;YAAExB,QAAQ;YAASC,SAAS;QAAM;IAC3C;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/forms/submitForm.ts"],"sourcesContent":["import 'server-only'\n\nimport type { BasePayload } from 'payload'\n\nimport { verifyTurnstile } from '../turnstile/index.js'\nimport { checkRateLimit } from './rateLimit.js'\nimport { validateSubmission } from './validateSubmission.js'\n\nexport type SubmitFormArgs = {\n /**\n * Name of the GDPR consent checkbox. A field with this name must be checked\n * for the submission to succeed (enforced server-side). Defaults to 'consent'.\n */\n consentFieldName?: string\n /** Submitted field data — shape matches the form's fields. */\n data: Record\n /** Form-builder form ID this submission belongs to. */\n formId: string\n /** Client IP — used for Turnstile and rate limiting. */\n ip?: string\n /**\n * Rate limit: max submissions per IP per minute. Defaults to 5.\n * Set to 0 to disable (e.g. when a real limiter sits in front).\n */\n maxPerMinute?: number\n payload: BasePayload\n /** Turnstile token; when present it is verified, when absent it is skipped. */\n turnstileToken?: string\n}\n\n/**\n * Why a submission failed — a code, never a user-facing string.\n *\n * The plugin knows what went wrong; it deliberately doesn't decide how to say\n * it. The frontend maps these to its own copy, in its own language, and renders\n * whatever component fits — a field error, a toast, a full message. The plugin\n * has no business choosing the wording or the locale.\n *\n * - `rate_limited` — too many submissions from this IP\n * - `turnstile` — bot check failed\n * - `validation` — a field is missing/too long, or unknown keys were sent;\n * `field` and `kind` narrow it down when a specific field is\n * at fault (absent for whole-payload problems like unknown keys)\n * - `not_found` — no form with this id\n * - `consent` — a required GDPR consent checkbox was left unchecked\n * - `error` — persistence failed unexpectedly\n */\nexport type SubmitFailure =\n | {\n /** The offending field's name, when one field is at fault. */\n field?: string\n /** What was wrong with it. */\n kind?: 'required' | 'too_long' | 'unknown_fields'\n reason: 'validation'\n success: false\n }\n | {\n field?: string\n /** A GDPR consent field existed on the form but wasn't checked. */\n reason: 'consent'\n success: false\n }\n | { reason: 'error'; success: false }\n | { reason: 'not_found'; success: false }\n | { reason: 'rate_limited'; success: false }\n | { reason: 'turnstile'; success: false }\n\nexport type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure\n\n/**\n * Handles a form submission end to end: rate limit, verify Turnstile, validate\n * against the form's own schema, then store.\n *\n * The order is cost-ascending on purpose — the cheapest checks reject first, so\n * a flood never reaches Turnstile's network call or the database.\n *\n * Emails aren't sent here. The form-builder sends whatever an editor configured\n * under the form's \"Emails\" tab (form-submissions hook → payload.sendEmail),\n * which goes out over the configured email adapter (mailAdapter). Storing the submission is enough.\n *\n * server-only: touches the Turnstile secret.\n */\nexport async function submitForm({\n consentFieldName,\n data,\n formId,\n ip,\n maxPerMinute = 5,\n payload,\n turnstileToken,\n}: SubmitFormArgs): Promise {\n // 1. Rate limit — cheapest gate, drops a flood before any real work.\n if (maxPerMinute > 0 && ip) {\n if (!checkRateLimit({ key: ip, max: maxPerMinute })) {\n return { reason: 'rate_limited', success: false }\n }\n }\n\n // 2. Turnstile — verify when a token is supplied; reject on failure.\n if (turnstileToken !== undefined) {\n const ok = await verifyTurnstile({ ip, payload, token: turnstileToken })\n if (!ok) {\n return { reason: 'turnstile', success: false }\n }\n }\n\n // 3. Validate against the form's schema. A public endpoint can't trust the\n // shape of `data` — drop unknown keys, enforce required, cap length.\n const validation = await validateSubmission(payload, formId, data, consentFieldName)\n if (!validation.ok) {\n if (validation.reason === 'not_found') {\n return { reason: 'not_found', success: false }\n }\n if (validation.reason === 'consent') {\n return { field: validation.field, reason: 'consent', success: false }\n }\n return {\n reason: 'validation',\n success: false,\n ...(validation.field ? { field: validation.field } : {}),\n ...(validation.kind ? { kind: validation.kind } : {}),\n }\n }\n\n // 4. Persist (form-builder shape: submissionData array). Triggers the email\n // hook. Only validated, known fields are stored.\n try {\n const submission = await payload.create({\n collection: 'form-submissions',\n data: {\n form: formId,\n submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({\n field,\n value: value == null ? '' : String(value),\n })),\n } as never,\n })\n return { submissionId: submission.id, success: true }\n } catch (err) {\n payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)\n return { reason: 'error', success: false }\n }\n}\n"],"names":["verifyTurnstile","checkRateLimit","validateSubmission","submitForm","consentFieldName","data","formId","ip","maxPerMinute","payload","turnstileToken","key","max","reason","success","undefined","ok","token","validation","field","kind","submission","create","collection","form","submissionData","Object","entries","cleaned","map","value","String","submissionId","id","err","logger","error","message"],"mappings":"AAAA,OAAO,cAAa;AAIpB,SAASA,eAAe,QAAQ,wBAAuB;AACvD,SAASC,cAAc,QAAQ,iBAAgB;AAC/C,SAASC,kBAAkB,QAAQ,0BAAyB;AA+D5D;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeC,WAAW,EAC/BC,gBAAgB,EAChBC,IAAI,EACJC,MAAM,EACNC,EAAE,EACFC,eAAe,CAAC,EAChBC,OAAO,EACPC,cAAc,EACC;IACf,qEAAqE;IACrE,IAAIF,eAAe,KAAKD,IAAI;QAC1B,IAAI,CAACN,eAAe;YAAEU,K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OoB,KAAK;QACZzB,QAAQ0B,MAAM,CAACC,KAAK,CAAC,CAAC,+BAA+B,EAAE,AAACF,IAAcG,OAAO,EAAE;QAC/E,OAAO;YAAExB,QAAQ;YAASC,SAAS;QAAM;IAC3C;AACF"} \ No newline at end of file diff --git a/dist/modules/links/buildLinkField.d.ts b/dist/modules/links/buildLinkField.d.ts index 8437b50..ca630cb 100644 --- a/dist/modules/links/buildLinkField.d.ts +++ b/dist/modules/links/buildLinkField.d.ts @@ -27,6 +27,14 @@ export type BuildLinkFieldOptions = { */ export declare function buildLinkField({ name, appearances, disableLabel, relationTo, required, uploadTo, }?: BuildLinkFieldOptions): GroupField; export type BuildLinksFieldOptions = { + /** + * What one row is called in the panel — the add button reads "Add ". + * Default { singular: 'Button', plural: 'Buttons' }; e.g. { singular: 'Link', plural: 'Links' } for a link list. + */ + labels?: { + plural: string; + singular: string; + }; /** Max number of buttons. Default 2. */ maxRows?: number; /** Field name. Default 'links'. */ @@ -36,4 +44,4 @@ export type BuildLinksFieldOptions = { * 0..N buttons — use for every "CTA(s)" of a section. Each row holds one * `link` (buildLinkField). Render: `links.map(({ id, link }) => )`. */ -export declare function buildLinksField({ name, maxRows, ...linkOptions }?: BuildLinksFieldOptions): ArrayField; +export declare function buildLinksField({ name, labels, maxRows, ...linkOptions }?: BuildLinksFieldOptions): ArrayField; diff --git a/dist/modules/links/buildLinkField.js b/dist/modules/links/buildLinkField.js index ecb08dc..d3be51f 100644 --- a/dist/modules/links/buildLinkField.js +++ b/dist/modules/links/buildLinkField.js @@ -1,3 +1,4 @@ +import { rowLabel } from 'src/modules/admin-ui/rowLabel.js'; const URL_PATTERN = /^(https?:\/\/|mailto:|tel:|#)/; /** * The ONE link shape for a project: a page, an external URL (also mailto:, @@ -117,16 +118,26 @@ const URL_PATTERN = /^(https?:\/\/|mailto:|tel:|#)/; /** * 0..N buttons — use for every "CTA(s)" of a section. Each row holds one * `link` (buildLinkField). Render: `links.map(({ id, link }) => )`. - */ export function buildLinksField({ name = 'links', maxRows = 2, ...linkOptions } = {}) { + */ export function buildLinksField({ name = 'links', labels = { + plural: 'Buttons', + singular: 'Button' +}, maxRows = 2, ...linkOptions } = {}) { return { name, type: 'array', admin: { - initCollapsed: true + initCollapsed: true, + // Rows read "Contact us" / "Download catalogue", not "Button 01". Needs the importMap entry. + components: rowLabel([ + 'link.label', + 'link.url' + ], labels.singular) }, fields: [ buildLinkField(linkOptions) ], + label: labels.plural, + labels, maxRows }; } diff --git a/dist/modules/links/buildLinkField.js.map b/dist/modules/links/buildLinkField.js.map index 69b623e..b978d89 100644 --- a/dist/modules/links/buildLinkField.js.map +++ b/dist/modules/links/buildLinkField.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/links/buildLinkField.ts"],"sourcesContent":["import type { ArrayField, Field, GroupField } from 'payload'\n\nexport type LinkAppearance = 'link' | 'primary' | 'secondary'\n\nexport type BuildLinkFieldOptions = {\n /** Visual styles the editor may pick. `false` → no appearance select. Default all three. */\n appearances?: false | LinkAppearance[]\n /** Hide the label — for links that wrap something (a whole card, an image). */\n disableLabel?: boolean\n /** Field name. Default 'link'. */\n name?: string\n /** Collection the \"Page\" option points at. Default 'pages'. */\n relationTo?: string\n required?: boolean\n /** Upload collection for \"File\" links (PDF, documents). Default 'media'. */\n uploadTo?: string\n}\n\nconst URL_PATTERN = /^(https?:\\/\\/|mailto:|tel:|#)/\n\ntype SiblingWithType = { type?: string } | undefined\n\n/**\n * The ONE link shape for a project: a page, an external URL (also mailto:,\n * tel:, #anchor) or an uploaded file — plus label, new-tab flag and visual\n * style. Every CTA, card link and download in every block uses this field, so\n * there is no zoo of ctaLabel / buttonUrl / pdfUrl fields and one renderer\n * (resolveLinkHref + the project's CMSLink) handles them all.\n *\n * Generates a named TypeScript type `CmsLink` in payload-types.ts.\n *\n * fields: [buildLinkField()] // single link\n * fields: [buildLinkField({ disableLabel: true, appearances: false })] // clickable card\n */\nexport function buildLinkField({\n name = 'link',\n appearances = ['primary', 'secondary', 'link'],\n disableLabel = false,\n relationTo = 'pages',\n required = false,\n uploadTo = 'media',\n}: BuildLinkFieldOptions = {}): GroupField {\n const fields: Field[] = [\n {\n type: 'row',\n fields: [\n {\n name: 'type',\n type: 'radio',\n admin: { layout: 'horizontal', width: '50%' },\n defaultValue: 'internal',\n options: [\n { label: 'Page', value: 'internal' },\n { label: 'URL', value: 'external' },\n { label: 'File', value: 'file' },\n ],\n },\n {\n name: 'newTab',\n type: 'checkbox',\n admin: { style: { alignSelf: 'flex-end' }, width: '50%' },\n label: 'Open in new tab',\n },\n ],\n },\n {\n name: 'page',\n type: 'relationship',\n admin: { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' },\n relationTo,\n required,\n },\n {\n name: 'url',\n type: 'text',\n admin: {\n condition: (_: unknown, s: SiblingWithType) => s?.type === 'external',\n description: 'Full URL (https://…), mailto:, tel: or #section-anchor.',\n },\n required,\n validate: (v: null | string | undefined) =>\n !v || URL_PATTERN.test(v) || 'Use https://…, mailto:, tel: or #anchor',\n },\n {\n name: 'file',\n type: 'upload',\n admin: {\n condition: (_: unknown, s: SiblingWithType) => s?.type === 'file',\n description: 'Upload a PDF / document / image. Never paste a file URL.',\n },\n relationTo: uploadTo,\n required,\n },\n ]\n\n if (!disableLabel) {\n fields.push({ name: 'label', type: 'text', localized: true, required })\n }\n\n if (appearances && appearances.length) {\n fields.push({\n name: 'appearance',\n type: 'select',\n defaultValue: appearances[0],\n options: appearances.map((a) => ({ label: a, value: a })),\n })\n }\n\n return {\n name,\n type: 'group',\n admin: { hideGutter: true },\n fields,\n interfaceName: 'CmsLink',\n }\n}\n\nexport type BuildLinksFieldOptions = {\n /** Max number of buttons. Default 2. */\n maxRows?: number\n /** Field name. Default 'links'. */\n name?: string\n} & Omit\n\n/**\n * 0..N buttons — use for every \"CTA(s)\" of a section. Each row holds one\n * `link` (buildLinkField). Render: `links.map(({ id, link }) => )`.\n */\nexport function buildLinksField({\n name = 'links',\n maxRows = 2,\n ...linkOptions\n}: BuildLinksFieldOptions = {}): ArrayField {\n return {\n name,\n type: 'array',\n admin: { initCollapsed: true },\n fields: [buildLinkField(linkOptions)],\n maxRows,\n }\n}\n"],"names":["URL_PATTERN","buildLinkField","name","appearances","disableLabel","relationTo","required","uploadTo","fields","type","admin","layout","width","defaultValue","options","label","value","style","alignSelf","condition","_","s","description","validate","v","test","push","localized","length","map","a","hideGutter","interfaceName","buildLinksField","maxRows","linkOptions","initCollapsed"],"mappings":"AAkBA,MAAMA,cAAc;AAIpB;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,eAAe,EAC7BC,OAAO,MAAM,EACbC,cAAc;IAAC;IAAW;IAAa;CAAO,EAC9CC,eAAe,KAAK,EACpBC,aAAa,OAAO,EACpBC,WAAW,KAAK,EAChBC,WAAW,OAAO,EACI,GAAG,CAAC,CAAC;IAC3B,MAAMC,SAAkB;QACtB;YACEC,MAAM;YACND,QAAQ;gBACN;oBACEN,MAAM;oBACNO,MAAM;oBACNC,OAAO;wBAAEC,QAAQ;wBAAcC,OAAO;oBAAM;oBAC5CC,cAAc;oBACdC,SAAS;wBACP;4BAAEC,OAAO;4BAAQC,OAAO;wBAAW;wBACnC;4BAAED,OAAO;4BAAOC,OAAO;wBAAW;wBAClC;4BAAED,OAAO;4BAAQC,OAAO;wBAAO;qBAChC;gBACH;gBACA;oBACEd,MAAM;oBACNO,MAAM;oBACNC,OAAO;wBAAEO,OAAO;4BAAEC,WAAW;wBAAW;wBAAGN,OAAO;oBAAM;oBACxDG,OAAO;gBACT;aACD;QACH;QACA;YACEb,MAAM;YACNO,MAAM;YACNC,OAAO;gBAAES,WAAW,CAACC,GAAYC,IAAuBA,GAAGZ,SAAS;YAAW;YAC/EJ;YACAC;QACF;QACA;YACEJ,MAAM;YACNO,MAAM;YACNC,OAAO;gBACLS,WAAW,CAACC,GAAYC,IAAuBA,GAAGZ,SAAS;gBAC3Da,aAAa;YACf;YACAhB;YACAiB,UAAU,CAACC,IACT,CAACA,KAAKxB,YAAYyB,IAAI,CAACD,MAAM;QACjC;QACA;YACEtB,MAAM;YACNO,MAAM;YACNC,OAAO;gBACLS,WAAW,CAACC,GAAYC,IAAuBA,GAAGZ,SAAS;gBAC3Da,aAAa;YACf;YACAjB,YAAYE;YACZD;QACF;KACD;IAED,IAAI,CAACF,cAAc;QACjBI,OAAOkB,IAAI,CAAC;YAAExB,MAAM;YAASO,MAAM;YAAQkB,WAAW;YAAMrB;QAAS;IACvE;IAEA,IAAIH,eAAeA,YAAYyB,MAAM,EAAE;QACrCpB,OAAOkB,IAAI,CAAC;YACVxB,MAAM;YACNO,MAAM;YACNI,cAAcV,WAAW,CAAC,EAAE;YAC5BW,SAASX,YAAY0B,GAAG,CAAC,CAACC,IAAO,CAAA;oBAAEf,OAAOe;oBAAGd,OAAOc;gBAAE,CAAA;QACxD;IACF;IAEA,OAAO;QACL5B;QACAO,MAAM;QACNC,OAAO;YAAEqB,YAAY;QAAK;QAC1BvB;QACAwB,eAAe;IACjB;AACF;AASA;;;CAGC,GACD,OAAO,SAASC,gBAAgB,EAC9B/B,OAAO,OAAO,EACdgC,UAAU,CAAC,EACX,GAAGC,aACoB,GAAG,CAAC,CAAC;IAC5B,OAAO;QACLjC;QACAO,MAAM;QACNC,OAAO;YAAE0B,eAAe;QAAK;QAC7B5B,QAAQ;YAACP,eAAekC;SAAa;QACrCD;IACF;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/links/buildLinkField.ts"],"sourcesContent":["import type { ArrayField, Field, GroupField } from 'payload'\n\nimport { rowLabel } from 'src/modules/admin-ui/rowLabel.js'\n\nexport type LinkAppearance = 'link' | 'primary' | 'secondary'\n\nexport type BuildLinkFieldOptions = {\n /** Visual styles the editor may pick. `false` → no appearance select. Default all three. */\n appearances?: false | LinkAppearance[]\n /** Hide the label — for links that wrap something (a whole card, an image). */\n disableLabel?: boolean\n /** Field name. Default 'link'. */\n name?: string\n /** Collection the \"Page\" option points at. Default 'pages'. */\n relationTo?: string\n required?: boolean\n /** Upload collection for \"File\" links (PDF, documents). Default 'media'. */\n uploadTo?: string\n}\n\nconst URL_PATTERN = /^(https?:\\/\\/|mailto:|tel:|#)/\n\ntype SiblingWithType = { type?: string } | undefined\n\n/**\n * The ONE link shape for a project: a page, an external URL (also mailto:,\n * tel:, #anchor) or an uploaded file — plus label, new-tab flag and visual\n * style. Every CTA, card link and download in every block uses this field, so\n * there is no zoo of ctaLabel / buttonUrl / pdfUrl fields and one renderer\n * (resolveLinkHref + the project's CMSLink) handles them all.\n *\n * Generates a named TypeScript type `CmsLink` in payload-types.ts.\n *\n * fields: [buildLinkField()] // single link\n * fields: [buildLinkField({ disableLabel: true, appearances: false })] // clickable card\n */\nexport function buildLinkField({\n name = 'link',\n appearances = ['primary', 'secondary', 'link'],\n disableLabel = false,\n relationTo = 'pages',\n required = false,\n uploadTo = 'media',\n}: BuildLinkFieldOptions = {}): GroupField {\n const fields: Field[] = [\n {\n type: 'row',\n fields: [\n {\n name: 'type',\n type: 'radio',\n admin: { layout: 'horizontal', width: '50%' },\n defaultValue: 'internal',\n options: [\n { label: 'Page', value: 'internal' },\n { label: 'URL', value: 'external' },\n { label: 'File', value: 'file' },\n ],\n },\n {\n name: 'newTab',\n type: 'checkbox',\n admin: { style: { alignSelf: 'flex-end' }, width: '50%' },\n label: 'Open in new tab',\n },\n ],\n },\n {\n name: 'page',\n type: 'relationship',\n admin: { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' },\n relationTo,\n required,\n },\n {\n name: 'url',\n type: 'text',\n admin: {\n condition: (_: unknown, s: SiblingWithType) => s?.type === 'external',\n description: 'Full URL (https://…), mailto:, tel: or #section-anchor.',\n },\n required,\n validate: (v: null | string | undefined) =>\n !v || URL_PATTERN.test(v) || 'Use https://…, mailto:, tel: or #anchor',\n },\n {\n name: 'file',\n type: 'upload',\n admin: {\n condition: (_: unknown, s: SiblingWithType) => s?.type === 'file',\n description: 'Upload a PDF / document / image. Never paste a file URL.',\n },\n relationTo: uploadTo,\n required,\n },\n ]\n\n if (!disableLabel) {\n fields.push({ name: 'label', type: 'text', localized: true, required })\n }\n\n if (appearances && appearances.length) {\n fields.push({\n name: 'appearance',\n type: 'select',\n defaultValue: appearances[0],\n options: appearances.map((a) => ({ label: a, value: a })),\n })\n }\n\n return {\n name,\n type: 'group',\n admin: { hideGutter: true },\n fields,\n interfaceName: 'CmsLink',\n }\n}\n\nexport type BuildLinksFieldOptions = {\n /**\n * What one row is called in the panel — the add button reads \"Add \".\n * Default { singular: 'Button', plural: 'Buttons' }; e.g. { singular: 'Link', plural: 'Links' } for a link list.\n */\n labels?: { plural: string; singular: string }\n /** Max number of buttons. Default 2. */\n maxRows?: number\n /** Field name. Default 'links'. */\n name?: string\n} & Omit\n\n/**\n * 0..N buttons — use for every \"CTA(s)\" of a section. Each row holds one\n * `link` (buildLinkField). Render: `links.map(({ id, link }) => )`.\n */\nexport function buildLinksField({\n name = 'links',\n labels = { plural: 'Buttons', singular: 'Button' },\n maxRows = 2,\n ...linkOptions\n}: BuildLinksFieldOptions = {}): ArrayField {\n return {\n name,\n type: 'array',\n admin: {\n initCollapsed: true,\n // Rows read \"Contact us\" / \"Download catalogue\", not \"Button 01\". Needs the importMap entry.\n components: rowLabel(['link.label', 'link.url'], labels.singular),\n },\n fields: [buildLinkField(linkOptions)],\n label: labels.plural,\n labels,\n maxRows,\n }\n}\n"],"names":["rowLabel","URL_PATTERN","buildLinkField","name","appearances","disableLabel","relationTo","required","uploadTo","fields","type","admin","layout","width","defaultValue","options","label","value","style","alignSelf","condition","_","s","description","validate","v","test","push","localized","length","map","a","hideGutter","interfaceName","buildLinksField","labels","plural","singular","maxRows","linkOptions","initCollapsed","components"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,mCAAkC;AAkB3D,MAAMC,cAAc;AAIpB;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,eAAe,EAC7BC,OAAO,MAAM,EACbC,cAAc;IAAC;IAAW;IAAa;CAAO,EAC9CC,eAAe,KAAK,EACpBC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CAACC,IAAO,CAAA;oBAAEf,OAAOe;oBAAGd,OAAOc;gBAAE,CAAA;QACxD;IACF;IAEA,OAAO;QACL5B;QACAO,MAAM;QACNC,OAAO;YAAEqB,YAAY;QAAK;QAC1BvB;QACAwB,eAAe;IACjB;AACF;AAcA;;;CAGC,GACD,OAAO,SAASC,gBAAgB,EAC9B/B,OAAO,OAAO,EACdgC,SAAS;IAAEC,QAAQ;IAAWC,UAAU;AAAS,CAAC,EAClDC,UAAU,CAAC,EACX,GAAGC,aACoB,GAAG,CAAC,CAAC;IAC5B,OAAO;QACLpC;QACAO,MAAM;QACNC,OAAO;YACL6B,eAAe;YACf,6FAA6F;YAC7FC,YAAYzC,SAAS;gBAAC;gBAAc;aAAW,EAAEmC,OAAOE,QAAQ;QAClE;QACA5B,QAAQ;YAACP,eAAeqC;SAAa;QACrCvB,OAAOmB,OAAOC,MAAM;QACpBD;QACAG;IACF;AACF"} \ No newline at end of file diff --git a/dist/modules/media/index.d.ts b/dist/modules/media/index.d.ts index 4f41aff..2a1fab5 100644 --- a/dist/modules/media/index.d.ts +++ b/dist/modules/media/index.d.ts @@ -1 +1,3 @@ export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js'; +export { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js'; +export type { OptimizeUploadOptions } from './optimizeUpload.js'; diff --git a/dist/modules/media/index.js b/dist/modules/media/index.js index c1e2a95..7970b96 100644 --- a/dist/modules/media/index.js +++ b/dist/modules/media/index.js @@ -1,3 +1,4 @@ export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js'; +export { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js'; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/modules/media/index.js.map b/dist/modules/media/index.js.map index 7462df6..4cad464 100644 --- a/dist/modules/media/index.js.map +++ b/dist/modules/media/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/media/index.ts"],"sourcesContent":["export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js'\n"],"names":["normalizeFilename","normalizeFilenameHook"],"mappings":"AAAA,SAASA,iBAAiB,EAAEC,qBAAqB,QAAQ,yBAAwB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/media/index.ts"],"sourcesContent":["export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js'\nexport { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js'\nexport type { OptimizeUploadOptions } from './optimizeUpload.js'\n"],"names":["normalizeFilename","normalizeFilenameHook","buildOptimizeUploadField","buildOptimizeUploadHook"],"mappings":"AAAA,SAASA,iBAAiB,EAAEC,qBAAqB,QAAQ,yBAAwB;AACjF,SAASC,wBAAwB,EAAEC,uBAAuB,QAAQ,sBAAqB"} \ No newline at end of file diff --git a/dist/modules/media/optimizeUpload.d.ts b/dist/modules/media/optimizeUpload.d.ts new file mode 100644 index 0000000..c29967b --- /dev/null +++ b/dist/modules/media/optimizeUpload.d.ts @@ -0,0 +1,45 @@ +import type { CheckboxField, CollectionBeforeOperationHook } from 'payload'; +/** + * Safety net for oversized uploads — NOT an image pipeline. The developer and + * editor are expected to upload prepared files; this only catches the 8 MB + * phone photo or the raw 300 MB video, and asks before touching anything. + * + * - JPG / PNG over the limits → upload is stopped with an explanation; the + * editor ticks "Optimize this upload" and saves again → converted to WebP, + * resized to maxImageWidth, auto-rotated, metadata (EXIF/GPS) removed. + * - Video over maxVideoBytes → stopped with export instructions (never + * transcoded — that needs ffmpeg and minutes of CPU per file). + * - Everything else (GIF, SVG, WebP, AVIF, PDF, animated images) → untouched. + * + * Uses the `sharp` instance passed to buildConfig({ sharp }) — the plugin + * never imports sharp itself. + */ +export type OptimizeUploadOptions = { + /** Name of the consent checkbox (buildOptimizeUploadField). Default 'optimizeOnUpload'. */ + consentField?: string; + /** Image size limit in bytes. Default 1.5 MB. */ + maxImageBytes?: number; + /** Image width limit in px — also the target width after optimizing. Default 2560. */ + maxImageWidth?: number; + /** Video size limit in bytes. Default 20 MB. `false` = no video limit. */ + maxVideoBytes?: false | number; + /** + * PNG handling: 'lossless' (default — safe for screenshots, logos, text) or + * 'lossy' (much smaller, may soften fine text). + */ + png?: 'lossless' | 'lossy'; + /** WebP quality for lossy output (JPG, and PNG when png: 'lossy'). Default 82. */ + quality?: number; +}; +/** + * Consent checkbox for the upload collection's sidebar. Unticked by default; + * only read when a file exceeds the limits. + */ +export declare function buildOptimizeUploadField(name?: string): CheckboxField; +/** + * beforeOperation hook for an upload collection (e.g. Media): + * + * hooks: { beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook()] }, + * fields: [..., buildOptimizeUploadField()], + */ +export declare function buildOptimizeUploadHook(options?: OptimizeUploadOptions): CollectionBeforeOperationHook; diff --git a/dist/modules/media/optimizeUpload.js b/dist/modules/media/optimizeUpload.js new file mode 100644 index 0000000..68c1aa5 --- /dev/null +++ b/dist/modules/media/optimizeUpload.js @@ -0,0 +1,107 @@ +import { readFile } from 'node:fs/promises'; +import { APIError } from 'payload'; +const OPTIMIZABLE = new Set([ + 'image/jpeg', + 'image/png' +]); +const MB = 1024 * 1024; +const fmt = (bytes)=>`${(bytes / MB).toFixed(1)} MB`; +/** + * Consent checkbox for the upload collection's sidebar. Unticked by default; + * only read when a file exceeds the limits. + */ export function buildOptimizeUploadField(name = 'optimizeOnUpload') { + return { + name, + type: 'checkbox', + admin: { + description: 'Only used when an image is too large: converts it to WebP, resizes it and removes metadata (EXIF/GPS). Prepared files are never changed.', + position: 'sidebar' + }, + defaultValue: false, + label: 'Optimize this upload' + }; +} +/** + * beforeOperation hook for an upload collection (e.g. Media): + * + * hooks: { beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook()] }, + * fields: [..., buildOptimizeUploadField()], + */ export function buildOptimizeUploadHook(options = {}) { + const { consentField = 'optimizeOnUpload', maxImageBytes = 1.5 * MB, maxImageWidth = 2560, maxVideoBytes = 20 * MB, png = 'lossless', quality = 82 } = options; + return async ({ args, operation, req })=>{ + if (operation !== 'create' && operation !== 'update') { + return; + } + const file = req.file; + if (!file) { + return; + } + const data = args.data; + const consent = Boolean(data?.[consentField]); + const size = file.size || file.data?.length || 0; + // --- Video: limit only, never transcoded --- + if (file.mimetype.startsWith('video/')) { + if (maxVideoBytes !== false && size > maxVideoBytes) { + throw new APIError(`Video is ${fmt(size)} (limit ${fmt(maxVideoBytes)}). Export it before uploading: ` + 'MP4 (H.264), 720p–1080p, about 2–4 Mbit/s, no audio track for background videos, ' + '"web optimized" / fast start enabled (e.g. HandBrake preset "Web").', 400, undefined, true); + } + return; + } + if (!OPTIMIZABLE.has(file.mimetype)) { + return; + } // GIF, SVG, WebP, AVIF, PDF… untouched + const sharp = req.payload.config.sharp; + const buffer = file.data && file.data.length > 0 ? file.data : file.tempFilePath ? await readFile(file.tempFilePath) : undefined; + if (!buffer) { + return; + } + let width; + let animated = false; + if (sharp) { + const meta = await sharp(buffer).metadata(); + width = meta.width; + animated = (meta.pages ?? 1) > 1; + } + if (animated) { + return; + } // APNG — converting would drop the animation + const tooHeavy = size > maxImageBytes; + const tooWide = width !== undefined && width > maxImageWidth; + if (!tooHeavy && !tooWide) { + return; + } + const problem = [ + tooHeavy ? `${fmt(size)} (limit ${fmt(maxImageBytes)})` : null, + tooWide ? `${width} px wide (limit ${maxImageWidth} px)` : null + ].filter(Boolean).join(', '); + if (!consent) { + throw new APIError(`Image is ${problem}. Tick "Optimize this upload" in the sidebar and save again to convert it ` + `to WebP (max ${maxImageWidth} px wide, metadata removed), or upload a smaller file.`, 400, undefined, true); + } + if (!sharp) { + throw new APIError('Image optimization needs sharp: pass it to buildConfig({ sharp }) in payload.config.ts.', 500, undefined, true); + } + const lossless = file.mimetype === 'image/png' && png === 'lossless'; + const output = await sharp(buffer).rotate() // apply EXIF orientation before metadata is dropped + .resize({ + width: maxImageWidth, + withoutEnlargement: true + }).webp(lossless ? { + lossless: true + } : { + quality + }).toBuffer(); + // Conversion didn't help (rare) and the width was fine → keep the original. + if (output.length >= size && !tooWide) { + return; + } + file.data = output; + file.size = output.length; + file.mimetype = 'image/webp'; + file.name = `${file.name.replace(/\.[^.]+$/, '')}.webp`; + delete file.tempFilePath; // Payload must read the new buffer, not the temp file + if (data) { + data[consentField] = false; + } // next oversized upload asks again + }; +} + +//# sourceMappingURL=optimizeUpload.js.map \ No newline at end of file diff --git a/dist/modules/media/optimizeUpload.js.map b/dist/modules/media/optimizeUpload.js.map new file mode 100644 index 0000000..85db65a --- /dev/null +++ b/dist/modules/media/optimizeUpload.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/media/optimizeUpload.ts"],"sourcesContent":["import type { CheckboxField, CollectionBeforeOperationHook } from 'payload'\n\nimport { readFile } from 'node:fs/promises'\nimport { APIError } from 'payload'\n\n/**\n * Safety net for oversized uploads — NOT an image pipeline. The developer and\n * editor are expected to upload prepared files; this only catches the 8 MB\n * phone photo or the raw 300 MB video, and asks before touching anything.\n *\n * - JPG / PNG over the limits → upload is stopped with an explanation; the\n * editor ticks \"Optimize this upload\" and saves again → converted to WebP,\n * resized to maxImageWidth, auto-rotated, metadata (EXIF/GPS) removed.\n * - Video over maxVideoBytes → stopped with export instructions (never\n * transcoded — that needs ffmpeg and minutes of CPU per file).\n * - Everything else (GIF, SVG, WebP, AVIF, PDF, animated images) → untouched.\n *\n * Uses the `sharp` instance passed to buildConfig({ sharp }) — the plugin\n * never imports sharp itself.\n */\n\nexport type OptimizeUploadOptions = {\n /** Name of the consent checkbox (buildOptimizeUploadField). Default 'optimizeOnUpload'. */\n consentField?: string\n /** Image size limit in bytes. Default 1.5 MB. */\n maxImageBytes?: number\n /** Image width limit in px — also the target width after optimizing. Default 2560. */\n maxImageWidth?: number\n /** Video size limit in bytes. Default 20 MB. `false` = no video limit. */\n maxVideoBytes?: false | number\n /**\n * PNG handling: 'lossless' (default — safe for screenshots, logos, text) or\n * 'lossy' (much smaller, may soften fine text).\n */\n png?: 'lossless' | 'lossy'\n /** WebP quality for lossy output (JPG, and PNG when png: 'lossy'). Default 82. */\n quality?: number\n}\n\nconst OPTIMIZABLE = new Set(['image/jpeg', 'image/png'])\nconst MB = 1024 * 1024\nconst fmt = (bytes: number) => `${(bytes / MB).toFixed(1)} MB`\n\n/**\n * Consent checkbox for the upload collection's sidebar. Unticked by default;\n * only read when a file exceeds the limits.\n */\nexport function buildOptimizeUploadField(name = 'optimizeOnUpload'): CheckboxField {\n return {\n name,\n type: 'checkbox',\n admin: {\n description:\n 'Only used when an image is too large: converts it to WebP, resizes it and removes metadata (EXIF/GPS). Prepared files are never changed.',\n position: 'sidebar',\n },\n defaultValue: false,\n label: 'Optimize this upload',\n }\n}\n\ntype UploadFile = {\n data: Buffer\n mimetype: string\n name: string\n size: number\n tempFilePath?: string\n}\n\n/**\n * beforeOperation hook for an upload collection (e.g. Media):\n *\n * hooks: { beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook()] },\n * fields: [..., buildOptimizeUploadField()],\n */\nexport function buildOptimizeUploadHook(\n options: OptimizeUploadOptions = {},\n): CollectionBeforeOperationHook {\n const {\n consentField = 'optimizeOnUpload',\n maxImageBytes = 1.5 * MB,\n maxImageWidth = 2560,\n maxVideoBytes = 20 * MB,\n png = 'lossless',\n quality = 82,\n } = options\n\n return async ({ args, operation, req }) => {\n if (operation !== 'create' && operation !== 'update') {return}\n const file = req.file as undefined | UploadFile\n if (!file) {return}\n\n const data = (args as { data?: Record }).data\n const consent = Boolean(data?.[consentField])\n const size = file.size || file.data?.length || 0\n\n // --- Video: limit only, never transcoded ---\n if (file.mimetype.startsWith('video/')) {\n if (maxVideoBytes !== false && size > maxVideoBytes) {\n throw new APIError(\n `Video is ${fmt(size)} (limit ${fmt(maxVideoBytes)}). Export it before uploading: ` +\n 'MP4 (H.264), 720p–1080p, about 2–4 Mbit/s, no audio track for background videos, ' +\n '\"web optimized\" / fast start enabled (e.g. HandBrake preset \"Web\").',\n 400,\n undefined,\n true,\n )\n }\n return\n }\n\n if (!OPTIMIZABLE.has(file.mimetype)) {return} // GIF, SVG, WebP, AVIF, PDF… untouched\n\n const sharp = req.payload.config.sharp\n const buffer =\n file.data && file.data.length > 0\n ? file.data\n : file.tempFilePath\n ? await readFile(file.tempFilePath)\n : undefined\n if (!buffer) {return}\n\n let width: number | undefined\n let animated = false\n if (sharp) {\n const meta = await sharp(buffer).metadata()\n width = meta.width\n animated = (meta.pages ?? 1) > 1\n }\n if (animated) {return} // APNG — converting would drop the animation\n\n const tooHeavy = size > maxImageBytes\n const tooWide = width !== undefined && width > maxImageWidth\n if (!tooHeavy && !tooWide) {return}\n\n const problem = [\n tooHeavy ? `${fmt(size)} (limit ${fmt(maxImageBytes)})` : null,\n tooWide ? `${width} px wide (limit ${maxImageWidth} px)` : null,\n ]\n .filter(Boolean)\n .join(', ')\n\n if (!consent) {\n throw new APIError(\n `Image is ${problem}. Tick \"Optimize this upload\" in the sidebar and save again to convert it ` +\n `to WebP (max ${maxImageWidth} px wide, metadata removed), or upload a smaller file.`,\n 400,\n undefined,\n true,\n )\n }\n\n if (!sharp) {\n throw new APIError(\n 'Image optimization needs sharp: pass it to buildConfig({ sharp }) in payload.config.ts.',\n 500,\n undefined,\n true,\n )\n }\n\n const lossless = file.mimetype === 'image/png' && png === 'lossless'\n const output = await sharp(buffer)\n .rotate() // apply EXIF orientation before metadata is dropped\n .resize({ width: maxImageWidth, withoutEnlargement: true })\n .webp(lossless ? { lossless: true } : { quality })\n .toBuffer()\n\n // Conversion didn't help (rare) and the width was fine → keep the original.\n if (output.length >= size && !tooWide) {return}\n\n file.data = output\n file.size = output.length\n file.mimetype = 'image/webp'\n file.name = `${file.name.replace(/\\.[^.]+$/, '')}.webp`\n delete file.tempFilePath // Payload must read the new buffer, not the temp file\n\n if (data) {data[consentField] = false} // next oversized upload asks again\n }\n}\n"],"names":["readFile","APIError","OPTIMIZABLE","Set","MB","fmt","bytes","toFixed","buildOptimizeUploadField","name","type","admin","description","position","defaultValue","label","buildOptimizeUploadHook","options","consentField","maxImageBytes","maxImageWidth","maxVideoBytes","png","quality","args","operation","req","file","data","consent","Boolean","size","length","mimetype","startsWith","undefined","has","sharp","payload","config","buffer","tempFilePath","width","animated","meta","metadata","pages","tooHeavy","tooWide","problem","filter","join","lossless","output","rotate","resize","withoutEnlargement","webp","toBuffer","replace"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,mBAAkB;AAC3C,SAASC,QAAQ,QAAQ,UAAS;AAoClC,MAAMC,cAAc,IAAIC,IAAI;IAAC;IAAc;CAAY;AACvD,MAAMC,KAAK,OAAO;AAClB,MAAMC,MAAM,CAACC,QAAkB,GAAG,AAACA,CAAAA,QAAQF,EAAC,EAAGG,OAAO,CAAC,GAAG,GAAG,CAAC;AAE9D;;;CAGC,GACD,OAAO,SAASC,yBAAyBC,OAAO,kBAAkB;IAChE,OAAO;QACLA;QACAC,MAAM;QACNC,OAAO;YACLC,aACE;YACFC,UAAU;QACZ;QACAC,cAAc;QACdC,OAAO;IACT;AACF;AAUA;;;;;CAKC,GACD,OAAO,SAASC,wBACdC,UAAiC,CAAC,CAAC;IAEnC,MAAM,EACJC,eAAe,kBAAkB,EACjCC,gBAAgB,MAAMf,EAAE,EACxBgB,gBAAgB,IAAI,EACpBC,gBAAgB,KAAKjB,EAAE,EACvBkB,MAAM,UAAU,EAChBC,UAAU,EAAE,EACb,GAAGN;IAEJ,OAAO,OAAO,EAAEO,IAAI,EAAEC,SAAS,EAAEC,GAAG,EAAE;QACpC,IAAID,cAAc,YAAYA,cAAc,UAAU;YAAC;QAAM;QAC7D,MAAME,OAAOD,IAAIC,IAAI;QACrB,IAAI,CAACA,MAAM;YAAC;QAAM;QAElB,MAAMC,OAAO,AAACJ,KAA4CI,IAAI;QAC9D,MAAMC,UAAUC,QAAQF,MAAM,CAACV,aAAa;QAC5C,MAAMa,OAAOJ,KAAKI,IAAI,IAAIJ,KAAKC,IAAI,EAAEI,UAAU;QAE/C,8CAA8C;QAC9C,IAAIL,KAAKM,QAAQ,CAACC,UAAU,CAAC,WAAW;YACtC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,CAAC,EACvF,KACAe,WACA;QAEJ;QAEA,IAAI,CAACE,OAAO;YACV,MAAM,IAAIpC,SACR,2FACA,KACAkC,WACA;QAEJ;QAEA,MAAMiB,WAAWzB,KAAKM,QAAQ,KAAK,eAAeX,QAAQ;QAC1D,MAAM+B,SAAS,MAAMhB,MAAMG,QACxBc,MAAM,GAAG,oDAAoD;SAC7DC,MAAM,CAAC;YAAEb,OAAOtB;YAAeoC,oBAAoB;QAAK,GACxDC,IAAI,CAACL,WAAW;YAAEA,UAAU;QAAK,IAAI;YAAE7B;QAAQ,GAC/CmC,QAAQ;QAEX,4EAA4E;QAC5E,IAAIL,OAAOrB,MAAM,IAAID,QAAQ,CAACiB,SAAS;YAAC;QAAM;QAE9CrB,KAAKC,IAAI,GAAGyB;QACZ1B,KAAKI,IAAI,GAAGsB,OAAOrB,MAAM;QACzBL,KAAKM,QAAQ,GAAG;QAChBN,KAAKlB,IAAI,GAAG,GAAGkB,KAAKlB,IAAI,CAACkD,OAAO,CAAC,YAAY,IAAI,KAAK,CAAC;QACvD,OAAOhC,KAAKc,YAAY,EAAC,sDAAsD;QAE/E,IAAIb,MAAM;YAACA,IAAI,CAACV,aAAa,GAAG;QAAK,EAAE,mCAAmC;IAC5E;AACF"} \ No newline at end of file diff --git a/docs/README.md b/docs/README.md index 8fcccd2..fd85893 100644 --- a/docs/README.md +++ b/docs/README.md @@ -3,9 +3,9 @@ | Kim jesteś | Czytaj | |---|---| | **Agent AI** pracujący w projekcie | [AGENT.md](./agent/AGENT.md) — reguły, struktura, budowa sekcji, kontrole przed „gotowe” | -| **Agent AI — skille** | [agent/skills/](./agent/skills) — 7 skilli `ipal-*` dla Antigravity/Claude Code (kopiowane do projektu: `pnpm ipal:skills`, AGENT.md §14) | +| **Agent AI — skille** | [agent/skills/](./agent/skills) — 14 skilli `ipal-*` dla Antigravity/Claude Code, w tym `ipal-site` (strona od briefu do raportu) i skrypty kontrolne (kopiowane do projektu: `pnpm ipal:skills`, AGENT.md §14) | | **Programista** | [PROGRAMISTA.md](./dev/PROGRAMISTA.md) — instalacja, nowy projekt, env, wdrożenie, aktualizacja, publikacja pluginu, Gitea | -| **Osoba prowadząca agenta AI** | [vibe.md](./dev/vibe.md) — gotowe polecenia do wklejenia, krok po kroku, moduł po module | +| **Osoba prowadząca agenta AI** | [vibe.md](./dev/vibe.md) — tryb autonomiczny (`/ipal-site`) i gotowe polecenia krok po kroku | Szczegóły API — jeden plik na moduł: @@ -22,7 +22,7 @@ Szczegóły API — jeden plik na moduł: | Formularze, useForm, honeypot | [forms.md](./forms.md) | | Hooki | [hooks.md](./hooks.md) | | i18n, proxy, przełącznik języka | [i18n.md](./i18n.md) | -| Linki / CTA: buildLinkField, buildLinksField, resolveLinkHref | [links.md](./links.md) | +| Linki / CTA: buildLinkField, buildLinksField, resolveLinkHref, rowLabel | [links.md](./links.md) | | Serwer MCP strony | [mcp.md](./mcp.md) | | Komunikaty formularzy | [notifications.md](./notifications.md) | | Strony systemowe, 404, generateStaticParams | [pages.md](./pages.md) | diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 0716165..318b6f6 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -17,7 +17,7 @@ ## 0. KOMPAS (jeśli zapamiętasz tylko to) 1. **ipal-kit jest obowiązkowy.** Funkcja, którą plugin ma, idzie przez plugin. - Brakuje czegoś → zgłoś (§1.3), nie łataj w projekcie. + Brakuje czegoś → raport (§1.3, ipal-plugin-gap) + oznaczone obejście, nie cicha łata. 2. **Nic na sztywno.** Tekst, obraz, link, plik, dane firmy → panel. Domeny, klucze → `.env`. Także w fallbacku `||` i w `catch`. 3. **Next 16 = `proxy.ts`.** NIGDY `middleware.ts`. @@ -27,6 +27,8 @@ FAQ/hero to bloki. 6. **Sekcja = kompozycja prymitywów.** `buildLinksField()` + ``, upload + ``, `
` + ``. Zero pól `ctaLabel`/`pdfUrl`. + **Panel przejrzysty** (§6.5a): powtarzalne = tablica „+ Add …” z `rowLabel`, nigdy + `cta1`/`cta2`; etykiety EN, krótkie; zero pustych pól „na zapas”. 7. **Renderery z pluginu:** `RenderBlocks` (nie `switch`), `RenderRichText` (nie własny parser Lexical), `useForm` (nie ręczna hydraulika formularza). 8. **Zero `any` i `@ts-ignore`.** Typy z `@/payload-types`, `unknown` + guard. @@ -35,6 +37,66 @@ --- +## 0a. JAK PRACUJESZ — samodzielnie, jak doświadczony pracownik + +Budujesz stronę od briefu do oddania. Człowiek dostarcza **decyzje biznesowe i +treści**, nie prowadzi Cię za rękę. Myślisz, przewidujesz problemy, sam je +rozwiązujesz i sam sprawdzasz swoją pracę. Do pełnej budowy użyj skilla +**ipal-site** — prowadzi przez wszystkie etapy. + +### Decydujesz sam (i zapisujesz decyzję w `AGENTS.md` → „Ustalenia projektu”) +- wybory techniczne w ramach tych reguł: podział na bloki, warianty, nazwy, + podkomponenty, kolejność pracy, refaktor własnego kodu, +- naprawę wszystkiego, co znajdą build, `ipal-audit`, `ipal-seo-check`, `ipal-consent-check`, +- wartości domyślne pluginu (limity mediów, ISR, robots) — chyba że brief mówi inaczej. + +### Pytasz tylko o to (zbierz pytania w **jedną listę**, nie po jednym) +- **dane, których nie ma** w briefie ani w panelu: języki, rynek, domena, dane firmy, + ID analityki i klucze integracji, adresy e-mail powiadomień; +- **decyzje nieodwracalne**: usuwanie treści, migracja bazy z treścią, zmiana slugów + opublikowanych stron, publikacja na produkcję; +- **sprzeczność** briefu z regułami (np. „ten tekst ma być na sztywno”) — od razu + z propozycją zgodnego rozwiązania; +- koszty i konta w usługach zewnętrznych. + +Brakuje treści? **Nie czekaj** — buduj strukturę, wpisz do panelu treść z briefu. +Nie wymyślaj danych firmy, cen, opinii ani liczb — wpisz w panelu wyraźny +placeholder `[DO UZUPEŁNIENIA: …]` i wypisz go w raporcie końcowym. + +### Przewidujesz — przed każdym zadaniem przejdź tę listę +| Pytanie | Typowa wpadka, której unikasz | +|---|---| +| Działa w **każdym języku**? (slug, treść, 404, przełącznik) | `/en/...` → 404, bo pusty slug EN | +| Strona zostaje **statyczna**? | `headers()`, `searchParams`, `cookies()` w drzewie stron (§4) | +| Zmiana schematu **gubi dane**? | zmiana nazwy pola bez migracji → **ipal-migrate-fields** | +| Build w kontenerze **bez bazy** przejdzie? | trasa czytająca bazę bez `force-dynamic` | +| Nowy skrypt / piksel / iframe **za zgodą**? | YouTube, mapa, czat ładowane przed zgodą (RODO) | +| Redaktor zmieni to **bez kodu**? | tekst, link albo obraz w JSX (§2) | +| **Wydajność**? | obraz poza ``, wideo bez `preload`, zapytania poza cache helperów | +| **Bezpieczeństwo**? | sekret w kliencie, brak `server-only`, Local API bez `overrideAccess: false` | +| Plugin **już to ma**? | własna wersja funkcji z ipal-kit (§1.1) | + +### Sprawdzasz sam, zanim powiesz „gotowe” +Pełny `ipal-audit`, `ipal-seo-check` i `ipal-consent-check` na zbudowanej +aplikacji (`pnpm build && pnpm start`), test redaktora (§11). Wyniki dołączasz +do raportu — bez nich zadanie nie jest skończone. + +### Gdy coś nie działa +Diagnozujesz (**ipal-debug**: objaw → przyczyna → poprawka), naprawiasz u źródła, +sprawdzasz ponownie. Nie zgłaszasz problemów, które możesz rozwiązać. + +### Raportujesz tylko gdy +- **ipal-kit ma błąd albo brakuje w nim funkcji** → **ipal-plugin-gap** (raport + + minimalne, oznaczone obejście — praca idzie dalej, nie czekasz), +- widzisz **usprawnienie ipal-kit** przydatne w wielu projektach → **ipal-plugin-gap** + (typ: usprawnienie), +- **zadanie jest skończone** → raport końcowy (format w **ipal-site**). + +Nie raportujesz postępu krok po kroku ani rzeczy, które sam naprawiłeś — te +trafiają jedną listą do raportu końcowego. + +--- + ## 1. ipal-kit JEST OBOWIĄZKOWY ### 1.1 Zanim napiszesz cokolwiek @@ -54,9 +116,10 @@ Reguła: **identyczne w każdym projekcie → plugin. Zależy od klienta → pro | hooki (revalidate, slugHistory, cross-locale), strony systemowe, storage R2 | wygląd (Tailwind, DESIGN.md) | ### 1.3 Gdy w pluginie czegoś brakuje albo nie działa -**Zatrzymaj się. Nie łataj w projekcie** (hook z zaszytą wartością, własny -helper, `as any`). To prawie zawsze znak, że plugin już to ma (sprawdź docs) albo -pluginowi tego brakuje. Przygotuj raport: +**Nie łataj po cichu** (hook z zaszytą wartością, własny helper, `as any`). To +prawie zawsze znak, że plugin już to ma (sprawdź docs) albo pluginowi tego brakuje. +Skill **ipal-plugin-gap**: raport + minimalne, oznaczone obejście +(`// WORKAROUND ipal-kit : …`), praca idzie dalej. Raport zawiera: - opis problemu / brakującej funkcji, - proponowane API (sygnatura funkcji / opcji), - dlaczego to uniwersalne (przyda się w innych projektach). @@ -244,7 +307,9 @@ Typ linku: strona / URL (też mailto, tel, #anchor) / **plik** (upload). Plik do pobrania = link typu `file`, nigdy pole `pdfUrl`. W `payload-types.ts`: `CmsLink`. **Obraz / wideo:** `{ name: 'media', type: 'upload', relationTo: 'media' }`. Kolekcja -`media` dopuszcza PDF, ma `alt` (required, localized) i `normalizeFilenameHook`. +`media` dopuszcza PDF, ma `alt` (required, localized), `normalizeFilenameHook` i siatkę na za duże +pliki `buildOptimizeUploadHook` + `buildOptimizeUploadField` (storage.md). Pliki przygotowujesz +przed wgraniem — hook tylko łapie wpadki i pyta o zgodę. **W projekcie (`src/fields/`)** — dwa małe helpery, kod w [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md): - `sectionHeaderField()` → grupa `header`: `eyebrow`, `heading`, `intro` (localized), @@ -266,10 +331,7 @@ Kod 1:1: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md). Każdy ma **`locale` dla bloków — raz, w trasie strony** (nigdy `headers()` w komponentach): ```tsx -const enhanceProps = ({ block }: { block: { blockType: string } }) => ({ - locale, - ...(block.blockType === 'formBlock' ? { turnstileSiteKey } : {}), -}) +const enhanceProps = () => ({ locale }) // Turnstile: w layoucie, nie props ``` ### 6.4 Warstwa 3 — sekcja = kompozycja @@ -327,6 +389,66 @@ Podkomponent jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/c Wyjątek tylko przy dwóch rzeczach tego samego rodzaju o różnej roli (`media` + `backgroundMedia`); rdzeń nazwy zostaje. +### 6.5a Panel redaktora — przejrzystość (każdy blok, kolekcja, global) + +Redaktor ma otworzyć blok i od razu wiedzieć, co gdzie jest — bez dziesiątek +pustych pól, bez zgadywania, bez numerowanych slotów. Schemat projektujesz dla +**redaktora**, nie dla komponentu. + +1. **Powtarzalne = jedna tablica z „+ Add …”**, nigdy numerowane pola. + `cta1Label`/`cta2Url`, `feature1Title`…`feature6Title`, `image2`, `phone2` → tablica: + przyciski `buildLinksField()` (panel: **„Add Button”**), elementy `items` z + `labels: { singular: 'Feature', plural: 'Features' }` (panel: **„Add Feature”**). + `maxRows` = ile mieści design, `minRows` tylko gdy bez elementu layout się sypie. +2. **Wiersz pokazuje swoją treść**: `admin: { initCollapsed: true, components: rowLabel('heading', 'Feature') }` + → zwinięte wiersze „Fast delivery”, „24/7 support” zamiast „Feature 01”. + `buildLinksField` ma to wbudowane (wiersz = etykieta przycisku). +3. **Panel po angielsku, krótko.** `label` 1–3 słowa, Sentence case („Heading”, + „Background”); `admin.description` tylko gdy etykieta nie wystarcza — jedno + zdanie ≤ 80 znaków: co to robi / gdzie to widać, z przykładem formatu + (`'Section id for #links, e.g. "pricing".'`), nigdy jak działa kod. Opcje selectów + z czytelnym `label` („Inverted (dark)”), nie surową wartością. +4. **Żadnych pól „na zapas”.** Każde pole jest wyświetlane przez komponent; puste + opcjonalne pole = element się nie renderuje (komponent to obsługuje). Pola + zależne ukryj: `admin.condition` (pola wideo tylko przy `mediaType: 'video'`, + pola wariantu tylko przy tym `variant`). Wariant wyglądu = `variant` (select) w + jednym bloku, nie drugi blok z kopią pól. +5. **Kolejność = kolejność na stronie**: `header` → treść → `media` → `items` → `links`. + Ustawienia techniczne (`settings`: anchor, tło, wariant) w **sidebarze**. + Blok z > ~10 polami → `tabs` (`Content`, `Media`, `Settings`); krótkie pary + (`type` + `newTab`, `width` + `height`) w `row` z `admin.width: '50%'`. +6. **Linki tylko przez pola linku.** Każdy przycisk/odnośnik to `buildLinkField` / + `buildLinksField` (strona z listy, URL, plik) — nigdy tekstowe pole URL do + własnej strony, nigdy link wpisany w JSX. +7. **Nazwy dla ludzi.** Blok: `labels: { singular: 'Feature grid', plural: 'Feature grids' }` + — nazwa tego, co redaktor widzi na stronie. Kolekcja: `admin.useAsTitle`, + `defaultColumns` (3–4), `admin.group` (`Content`, `Settings`, `Forms`). +8. **`required` oszczędnie** — tylko gdy bez wartości sekcja jest zepsuta (np. + `heading` elementu listy, `alt` obrazu). Selecty i checkboxy z `defaultValue`. + +```ts +// ŹLE — 14 pól, połowa zawsze pusta, numerowane sloty, link jako tekst +{ name: 'title', type: 'text' }, { name: 'subtitle', type: 'text' }, +{ name: 'cta1Label', type: 'text' }, { name: 'cta1Url', type: 'text' }, +{ name: 'cta2Label', type: 'text' }, { name: 'cta2Url', type: 'text' }, +{ name: 'feature1Title', type: 'text' }, { name: 'feature1Text', type: 'text' }, // …feature3 +{ name: 'bgColor', type: 'text', admin: { description: 'Kolor tła sekcji w hex, używany w className komponentu' } }, + +// DOBRZE — 4 pozycje w panelu, rośnie przyciskiem „+ Add …” +sectionHeaderField(), // Eyebrow / Heading / Intro +{ name: 'items', type: 'array', labels: { singular: 'Feature', plural: 'Features' }, maxRows: 6, + admin: { initCollapsed: true, components: rowLabel('heading', 'Feature') }, + fields: [{ name: 'heading', type: 'text', localized: true, required: true }, { name: 'text', type: 'textarea', localized: true }] }, +buildLinksField(), // „+ Add Button” +sectionSettingsField(), // sidebar: anchor, background +``` + +**Test pustego bloku** (po każdym nowym bloku, w panelu): dodaj blok na stronie → +na starcie widać ≤ 6 pozycji, wszystko po angielsku, przyciski i elementy dodaje +się „+ Add …”, zwinięte wiersze mają czytelne nazwy, nic nie wymaga wiedzy o kodzie. +Kontrole automatyczne: `ipal-audit` (sekcja „panel:”). Po dodaniu `rowLabel` w +projekcie: `pnpm payload generate:importmap`. + ### 6.6 Antywzorce → poprawka ```ts @@ -456,7 +578,7 @@ Przykładowy `styles.css`: [kod-sekcji.md](./skills/ipal-block/resources/kod-sek | Metadata, sitemap, JSON-LD, llms.txt | `generatePageMetadata` (z `createContentHelpers`), `sitemap`, `build*JsonLd`, `createLlmsTxtRoute` | seo.md | | Consent, analytics, pixele | `ConsentProvider`, `CookieBanner`, `Analytics` (wewnątrz providera) | consent.md, analytics.md | | Nagłówki, CSP, 2FA | `buildSecurityHeaders`, `buildCsp`, `twoFactor` (wstrzyknięty `payloadTotp`) | security.md | -| Media, R2 | `buildR2Storage(['media'], { s3Storage })` (adapter wstrzyknięty), `normalizeFilenameHook`, `MediaPreconnect` | storage.md | +| Media, R2 | `buildR2Storage(['media'], { s3Storage })` (adapter wstrzyknięty), `normalizeFilenameHook`, `buildOptimizeUploadHook` + `buildOptimizeUploadField`, `MediaPreconnect` | storage.md | | Email | `email: mailAdapter()` | email.md | | Walidacja env | `assertEnv(ipalEnvRules({...}))` | env.md | @@ -646,13 +768,24 @@ zadanie pasuje — ręcznie: `/`. | Skill | Kiedy | |---|---| -| `ipal-setup` | nowy projekt od zera | -| `ipal-block` | nowa albo poprawiana sekcja (blok) | +| `ipal-site` | **cała strona od briefu do raportu** — prowadzi przez pozostałe skille (§0a) | +| `ipal-setup` | nowy projekt od zera (fundament) | +| `ipal-block` | nowa albo poprawiana sekcja (blok) — schemat, panel (§6.5a), komponent | | `ipal-collection` | „potrzebny blog / produkty / …” — zanim powstanie plik w `src/collections` | | `ipal-nav` | nagłówek, menu, stopka, dane firmy | +| `ipal-form` | formularz z panelu: renderer, akcja `submitForm`, Turnstile, maile, GTM | +| `ipal-locale-add` | nowy język — konfiguracja, treść, skrypt `locale-coverage` | +| `ipal-migrate-fields` | zmiana pól, w których jest już treść — 3 fazy, skrypt z dry-run | | `ipal-upgrade` | aktualizacja ipal-kit w istniejącym projekcie | -| `ipal-audit` | przed każdym „gotowe” — skrypt z kontrolami §11 + tsc + build | -| `ipal-plugin-gap` | pluginowi czegoś brakuje albo nie działa — raport zamiast łatki | +| `ipal-debug` | cokolwiek nie działa — procedura + tabela objaw → przyczyna → naprawa | +| `ipal-audit` | przed każdym „gotowe” — kontrole §11 + panel (§6.5a) + hardkody w JSX + tsc + build | +| `ipal-seo-check` | działająca strona oczami Googlebota (head, canonical, hreflang, sitemap, 404) | +| `ipal-consent-check` | przeglądarka: zero pikseli i cookies śledzących przed zgodą | +| `ipal-plugin-gap` | ipal-kit ma błąd albo brakuje funkcji — raport + oznaczone obejście, praca idzie dalej | + +Skrypty w skillach uruchamiasz, nie czytasz (wynik wystarcza): `ipal-audit/scripts/audit.sh`, +`ipal-seo-check/scripts/seo-check.mjs`, `ipal-consent-check/scripts/consent-check.mjs`, +`ipal-locale-add/scripts/locale-coverage.ts`; szablony do skopiowania w `resources/`. **Instalacja w projekcie** (raz i po każdej aktualizacji ipal-kit) — skrypt w `package.json` projektu: diff --git a/docs/agent/skills/ipal-audit/scripts/audit.sh b/docs/agent/skills/ipal-audit/scripts/audit.sh index f5cbef4..f05d92d 100644 --- a/docs/agent/skills/ipal-audit/scripts/audit.sh +++ b/docs/agent/skills/ipal-audit/scripts/audit.sh @@ -49,6 +49,12 @@ UI=$(dirs src/blocks src/components) echo "ipal-audit — $(pwd)" +# --- Skill templates must not be compiled as project code --- +if [ -d .agents ] && [ -f tsconfig.json ]; then + report ERROR "tsconfig.json does not exclude .agents" "skill templates (.ts/.tsx) break tsc / next build — \"exclude\": [\"node_modules\", \".agents\"]" \ + "$(grep -qE '"exclude"[^]]*\.agents' tsconfig.json || echo tsconfig.json)" +fi + # --- Architecture (AGENT.md §4) --- report ERROR "middleware.ts exists" "§4.1 Next 16 uses proxy.ts only" \ "$(ls src/middleware.ts middleware.ts 2>/dev/null)" @@ -93,6 +99,9 @@ if [ -n "$BLOCKS" ]; then report ERROR "raw / in blocks" "§6.3 links from the panel render via CMSLink" \ "$(g '<(a|Link)[ >]' $BLOCKS --include=*.tsx)" + report ERROR "hardcoded text in blocks" "§2 every visible text comes from the panel (localized field)" \ + "$(node "$(dirname "$0")/jsx-text.mjs" $BLOCKS 2>/dev/null)" + report WARNING "inline in blocks" "§6.10 icons via media upload or Icon map" \ "$(g ']' $BLOCKS --include=*.tsx)" @@ -103,6 +112,11 @@ if [ -n "$BLOCKS" ]; then "$(g "from '\./Component'|/Component'" $BLOCKS --include=config.ts)" fi +if [ -d src/components ]; then + report WARNING "hardcoded text in components/layout" "§2 texts and a11y labels from the panel — keep only symbols/numbers in code" \ + "$(node "$(dirname "$0")/jsx-text.mjs" src/components 2>/dev/null)" +fi + if [ -n "$UI" ]; then report ERROR "hex colors in classes" "§6.11 use design tokens (bg-primary…)" \ "$(g '(bg|text|border|from|to|via|fill|stroke)-\[#' $UI --include=*.tsx)" @@ -125,6 +139,17 @@ if [ -d src/collections ]; then "$(ls src/collections | grep -viE '^(pages|media|users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')" fi +# --- Editor panel clarity (§6.5a) --- +SCHEMA=$(dirs src/blocks src/collections src/globals src/fields) +if [ -n "$SCHEMA" ]; then + PANEL=$(node "$(dirname "$0")/panel-check.mjs" $SCHEMA) + while IFS= read -r rule; do + [ -z "$rule" ] && continue + level=${rule%%|*}; rest=${rule#*|} + report "$level" "panel: ${rest%%|*}" "§6.5a editor panel" "$(printf '%s\n' "$PANEL" | grep -F "$level|${rest%%|*}|" | cut -d'|' -f3-)" + done <<< "$(printf '%s\n' "$PANEL" | cut -d'|' -f1-2 | sort -u)" +fi + # --- Plugin duplicates (§1, §7) --- report ERROR "own block renderer switch" "§7 use RenderBlocks + registry" \ "$(g 'switch *\(.*blockType' src --include=*.tsx --include=*.ts)" diff --git a/docs/agent/skills/ipal-audit/scripts/jsx-text.mjs b/docs/agent/skills/ipal-audit/scripts/jsx-text.mjs new file mode 100644 index 0000000..f194987 --- /dev/null +++ b/docs/agent/skills/ipal-audit/scripts/jsx-text.mjs @@ -0,0 +1,56 @@ +#!/usr/bin/env node +// Finds user-visible text hardcoded in JSX (AGENT.md §2: everything visible comes from the panel). +// node jsx-text.mjs [ …] → prints "file:line: text" per finding, exit 0 +// Detects: +// - text between HTML text tags:

Nasze usługi

,

\n Lorem…\n

, więcej < +// - text attributes with words: alt="Logo firmy", placeholder="Twój e-mail", aria-label="Zamknij" +// Ignores comments, {expressions}, digits/punctuation/symbols only (404, →, ☰, ·). +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { join } from 'node:path' + +const TEXT_TAGS = + 'h1|h2|h3|h4|h5|h6|p|span|a|button|li|label|strong|em|b|i|small|div|section|article|header|footer|main|nav|td|th|dt|dd|figcaption|blockquote|option|legend|summary|caption|q|cite|time|mark' +// Opening tags: HTML text tags or Capitalized components (), never preceded by an +// identifier char — that excludes TS generics like useState( … ). +const OPEN_OR_CLOSE = new RegExp( + `(?:(?]*)?>|)([^<>{}]*)(?=<|\\{)`, + 'g', +) +const ATTR = /\b(alt|title|placeholder|aria-label|label)=("([^"]*)"|'([^']*)')/g +const WORD = /\p{L}{2,}/u +// Text right after a closing/self-closing tag may be the JS that follows the JSX +// expression (` : null`, `) }`, `

\n const id = …`) — not visible text. +const JS_CODE = /(^|\s)(return|const|let|var|if|else|export|import|await|typeof)\b|=>|[=;`]|^\s*[:?)\]}]|&&|\|\|/ + +const files = [] +const walk = (p) => { + let st + try { st = statSync(p) } catch { return } + if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n)) + else if (p.endsWith('.tsx')) files.push(p) +} +process.argv.slice(2).forEach(walk) + +// Blank out comments but keep line numbers. +const stripComments = (src) => + src + .replace(/\{\/\*[\s\S]*?\*\/\}/g, (m) => m.replace(/[^\n]/g, ' ')) + .replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')) + .replace(/(^|[^:"'`])\/\/.*$/gm, (m, p) => p + ' '.repeat(m.length - p.length)) + +const lineOf = (src, idx) => src.slice(0, idx).split('\n').length + +for (const file of files) { + const src = stripComments(readFileSync(file, 'utf8')) + for (const m of src.matchAll(OPEN_OR_CLOSE)) { + const text = m[1].replace(/\s+/g, ' ').trim() + if (!text || !WORD.test(text) || JS_CODE.test(text)) continue + if (/&[a-z]+;/.test(text) && !WORD.test(text.replace(/&[a-z]+;/g, ''))) continue + console.log(`${file}:${lineOf(src, m.index + m[0].length - m[1].length)}: ${text.slice(0, 80)}`) + } + for (const m of src.matchAll(ATTR)) { + const value = m[3] ?? m[4] ?? '' + if (!WORD.test(value)) continue + console.log(`${file}:${lineOf(src, m.index)}: ${m[1]}="${value.slice(0, 60)}"`) + } +} diff --git a/docs/agent/skills/ipal-audit/scripts/panel-check.mjs b/docs/agent/skills/ipal-audit/scripts/panel-check.mjs new file mode 100644 index 0000000..2a80f59 --- /dev/null +++ b/docs/agent/skills/ipal-audit/scripts/panel-check.mjs @@ -0,0 +1,54 @@ +#!/usr/bin/env node +// Editor-panel clarity checks (AGENT.md §6.5a): prints "LEVEL|rule|file:line: detail", exit 0. +// node panel-check.mjs src/blocks src/collections src/globals src/fields +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { join } from 'node:path' + +const files = [] +const walk = (p) => { + let st + try { st = statSync(p) } catch { return } + if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n)) + else if (/\.ts$/.test(p) && !/Component|\.d\.ts$/.test(p)) files.push(p) +} +process.argv.slice(2).forEach(walk) + +const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/ +const lineOf = (src, i) => src.slice(0, i).split('\n').length +const out = (level, rule, file, src, i, detail) => console.log(`${level}|${rule}|${file}:${lineOf(src, i)}: ${detail}`) +const strip = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:])\/\/.*$/gm, (m, p) => p + ' '.repeat(m.length - p.length)) + +for (const file of files) { + const src = strip(readFileSync(file, 'utf8')) + + // numbered slots: cta1Label, feature2Title, image3, phone2 → array with "+ Add …" + for (const m of src.matchAll(/name:\s*['"]([a-zA-Z]+[0-9]+[a-zA-Z0-9]*)['"]/g)) { + if (/^(h[1-6]|x[0-9]|[a-z]?2fa)$/i.test(m[1])) continue + out('ERROR', 'numbered fields → one array field with labels {singular, plural} ("+ Add …")', file, src, m.index, m[1]) + } + + // panel text must be English and short + for (const m of src.matchAll(/\b(label|description|singular|plural|placeholder)\s*:\s*(['"`])((?:(?!\2).)*)\2/g)) { + const text = m[3] + if (POLISH.test(text)) out('WARNING', 'panel is English — labels/descriptions in English', file, src, m.index, `${m[1]}: "${text.slice(0, 60)}"`) + else if (m[1] === 'description' && text.length > 120) out('WARNING', 'description over 120 chars — one short sentence: what it does / where it shows', file, src, m.index, `${text.length} chars`) + } + + // arrays: labels (→ "Add Feature" button) + rowLabel (→ readable rows) + for (const m of src.matchAll(/type:\s*['"]array['"]/g)) { + const before = src.slice(0, m.index) + const start = Math.max(before.lastIndexOf('name:'), before.lastIndexOf('{')) + const fieldsAt = src.indexOf('fields:', m.index) + const head = src.slice(start < 0 ? m.index : start, fieldsAt < 0 ? m.index + 400 : fieldsAt) + const name = head.match(/name:\s*['"](\w+)['"]/)?.[1] ?? '?' + if (!/\blabels\s*:/.test(head)) out('WARNING', 'array without labels {singular, plural} — panel shows "Add Row"', file, src, m.index, name) + if (!/rowLabel|RowLabel/.test(head)) out('WARNING', 'array without rowLabel() — rows read "Item 01" instead of their content', file, src, m.index, name) + } + + // too many fields in one block config → tabs / condition / arrays / variant + if (/\/blocks\/[^/]+\/config\.ts$/.test(file)) { + const n = (src.match(/name:\s*['"]/g) ?? []).length + const hasTabs = /type:\s*['"]tabs['"]/.test(src) + if (n > 14 && !hasTabs) out('WARNING', 'block has many fields and no tabs — tabs Content/Media/Settings, admin.condition, arrays', file, src, 0, `${n} fields`) + } +} diff --git a/docs/agent/skills/ipal-block/SKILL.md b/docs/agent/skills/ipal-block/SKILL.md index 780b108..6eb90da 100644 --- a/docs/agent/skills/ipal-block/SKILL.md +++ b/docs/agent/skills/ipal-block/SKILL.md @@ -1,6 +1,6 @@ --- name: ipal-block -description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — shared fields (sectionHeaderField, buildLinksField, buildLinkField, sectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component. +description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — a clean editor panel (repeatable things as "+ Add …" arrays with rowLabel, never cta1/cta2 slots, short English labels, no empty spare fields), shared fields (sectionHeaderField, buildLinksField, buildLinkField, sectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component. --- # ipal-block @@ -15,7 +15,7 @@ Linki (`buildLinkField`, `buildLinksField`, `resolveLinkHref`) są w pluginie Brakuje → najpierw utwórz je 1:1 z `resources/kod-sekcji.md` (ten skill) (i powiedz o tym użytkownikowi). Nie pisz własnych wersji. -## 1. Plan (pokaż i czekaj na OK) +## 1. Plan (zapisz w 3–5 punktach, potem od razu kod — AGENT.md §0a) - slug bloku (camelCase), nazwa folderu (PascalCase), - lista pól **tylko** ze słownika AGENT.md §6.5: `header`, `media`, `links`, `link`, `items` (+ `heading`, `text`, `content`), `settings`, @@ -28,7 +28,12 @@ Wzorce plików (Hero, FeatureGrid + FeatureCard): `resources/kod-sekcji.md`. 1. `src/blocks//config.ts` — `interfaceName: 'Block'`, pola z planu, zawsze `sectionSettingsField()`. CTA = `buildLinksField()`, nigdy pola `cta*`/`button*`. - Plik do pobrania = link typu `file`. Etykiety i opisy pól po angielsku. + Plik do pobrania = link typu `file`. **Panel wg AGENT.md §6.5a:** + - powtarzalne → tablica z `labels: { singular, plural }` + `admin: { initCollapsed: true, components: rowLabel('heading', '') }`, `maxRows` z designu; + - zero numerowanych pól (`cta1`, `feature2Title`, `image3`) i pól „na zapas”; + - etykiety EN 1–3 słowa, `description` tylko gdy potrzebny (≤ 80 znaków, co/gdzie, przykład); + - pola zależne `admin.condition`, wariant = `variant` select, > ~10 pól → `tabs`; + - blok: `labels: { singular: 'Feature grid', plural: 'Feature grids' }`. 2. `src/blocks//Component.tsx` — nazwany eksport, typ z `@/payload-types` (`Block & { locale: string }`), struktura: `
` → `` → treść z ``, ``, @@ -40,6 +45,9 @@ Wzorce plików (Hero, FeatureGrid + FeatureCard): `resources/kod-sekcji.md`. ## 3. Weryfikacja - `Component.tsx` ≤ ~80 linii JSX. +- **Test pustego bloku** w panelu: ≤ 6 pozycji na starcie, wszystko po angielsku, + „+ Add Button / Add Feature”, zwinięte wiersze z treścią, każde pole coś wyświetla. + Pierwszy `rowLabel` w projekcie → `pnpm payload generate:importmap`. - Uruchom skill **ipal-audit** (`--quick`), napraw wszystkie `[ERROR]`. - Refaktor istniejącego bloku ze zmianą nazw pól: **najpierw migracja danych** (stare pole → nowe), dopiero potem usunięcie starych pól (AGENT.md §6.7). diff --git a/docs/agent/skills/ipal-block/resources/kod-sekcji.md b/docs/agent/skills/ipal-block/resources/kod-sekcji.md index 1d1f8a5..560bfbf 100644 --- a/docs/agent/skills/ipal-block/resources/kod-sekcji.md +++ b/docs/agent/skills/ipal-block/resources/kod-sekcji.md @@ -40,9 +40,9 @@ export function sectionHeaderField(name = 'header'): GroupField { type: 'group', interfaceName: 'SectionHeaderData', fields: [ - { name: 'eyebrow', type: 'text', localized: true }, + { name: 'eyebrow', type: 'text', localized: true, admin: { description: 'Small line above the heading. Optional.' } }, { name: 'heading', type: 'text', localized: true }, - { name: 'intro', type: 'textarea', localized: true }, + { name: 'intro', type: 'textarea', localized: true, admin: { rows: 3 } }, ], } } @@ -51,6 +51,7 @@ export function sectionSettingsField(): GroupField { return { name: 'settings', type: 'group', + label: 'Section settings', interfaceName: 'SectionSettings', admin: { position: 'sidebar' }, fields: [ @@ -63,7 +64,11 @@ export function sectionSettingsField(): GroupField { name: 'background', type: 'select', defaultValue: 'default', - options: ['default', 'muted', 'inverted'].map((v) => ({ label: v, value: v })), + options: [ + { label: 'Default', value: 'default' }, + { label: 'Muted', value: 'muted' }, + { label: 'Inverted (dark)', value: 'inverted' }, + ], }, ], } @@ -143,14 +148,19 @@ type Props = { sizes?: string priority?: boolean className?: string + /** Poster image URL for videos (shown before playback). */ + poster?: string } -export function Media({ resource, sizes = '100vw', priority = false, className }: Props) { +export function Media({ resource, sizes = '100vw', priority = false, className, poster }: Props) { if (!resource || typeof resource !== 'object' || !resource.url) return null const { url, alt, width, height, mimeType } = resource if (mimeType?.startsWith('video/')) { - return