diff --git a/agents.md b/agents.md index dfc5bc0..78041f6 100644 --- a/agents.md +++ b/agents.md @@ -234,6 +234,8 @@ Ten plik to skondensowane reguły. Szczegóły w `node_modules/@intecion/ipal-ki | Hooki (revalidate, slug history, cross-locale sync, ochrona) | `hooks.md` | | Redirecty 301/308 (resolveRedirect) | `content.md` | | Walidacja ENV na starcie (assertEnv) | `env.md` | +| Czytelność dla AI: Markdown per strona, llms-full, boty AI w robots | `content.md`, `seo.md` | +| Serwer MCP strony (Claude podłącza się do treści) | `mcp.md` | | Bezpieczeństwo, CSP, COOP | `security.md` | | Formularze, Turnstile, submitForm, useForm/useContactForm | `forms.md`, `turnstile.md` | | i18n, strona jednojęzyczna, ścieżki | `i18n.md` | diff --git a/dist/index.d.ts b/dist/index.d.ts index b0e013c..4ff67bd 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -7,8 +7,9 @@ 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, buildArchivePath, buildEntryPath, getArchiveEntries, parsePageParam, resolveRedirect, resolveRoute, } from './modules/content/index.js'; +export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveRedirect, resolveRoute, searchContent, } from './modules/content/index.js'; export 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'; @@ -32,6 +33,7 @@ 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 { 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'; @@ -39,6 +41,7 @@ export type { PagesOption, SystemPageRole } from './modules/pages/index.js'; export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/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 { lexicalToMarkdown } from './modules/richtext/index.js'; export { buildSecurityHeaders } from './modules/security/index.js'; export { buildCsp } from './modules/security/index.js'; export type { BuildCspArgs } from './modules/security/index.js'; @@ -46,10 +49,12 @@ export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/securit export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'; export { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js'; export type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js'; -export { buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta, } from './modules/seo/index.js'; +export { 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 { 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 { buildArticleJsonLd } from './modules/seo/index.js'; diff --git a/dist/index.js b/dist/index.js index e8c86ce..2dd1ebb 100644 --- a/dist/index.js +++ b/dist/index.js @@ -2,7 +2,7 @@ export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSe export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js'; export { getAnalyticsConfig } from './modules/analytics/index.js'; export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, DEFAULT_CONSENT, getConsentTexts, parseConsent, REJECT_ALL_CONSENT, serializeConsent, setDefaultConsent, updateConsent } from './modules/consent/index.js'; -export { archiveFieldName, buildArchivePath, buildEntryPath, getArchiveEntries, parsePageParam, resolveRedirect, resolveRoute } from './modules/content/index.js'; +export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveRedirect, resolveRoute, searchContent } from './modules/content/index.js'; export { graphAdapter } from './modules/email/graphAdapter.js'; export { mailAdapter } from './modules/email/mailAdapter.js'; // Imported straight from the file, NOT from ./modules/email/index.js — that @@ -25,17 +25,23 @@ export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefiniti 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'; +// 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'; export { buildSecurityHeaders } from './modules/security/index.js'; export { buildCsp } from './modules/security/index.js'; export { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js'; -export { buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta } from './modules/seo/index.js'; +export { 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 { buildSpeakableJsonLd } from './modules/seo/index.js'; +export { buildSummaryField } from './modules/seo/index.js'; export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js'; // Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage. export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js'; diff --git a/dist/index.js.map b/dist/index.js.map index c5a5a34..38cdb84 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 buildArchivePath,\n buildEntryPath,\n getArchiveEntries,\n parsePageParam,\n resolveRedirect,\n resolveRoute,\n} from './modules/content/index.js'\nexport type { ArchiveEntries } 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'\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 { 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'\nexport { buildSecurityHeaders } from './modules/security/index.js'\nexport { buildCsp } from './modules/security/index.js'\n\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 { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js'\nexport type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js'\nexport {\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 {\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","buildArchivePath","buildEntryPath","getArchiveEntries","parsePageParam","resolveRedirect","resolveRoute","graphAdapter","mailAdapter","panelSmtpAdapter","assertEnv","ipalEnvRules","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","normalizeFilename","normalizeFilenameHook","getNotificationTexts","NOTIFICATION_FALLBACK","resolveFormMessage","ALL_SYSTEM_PAGE_ROLES","getSystemPagePath","getGlobal","getSiteIntegrations","getSiteSettings","SITE_INTEGRATIONS_SLUG","SITE_SETTINGS_SLUG","buildSecurityHeaders","buildCsp","buildHreflangAlternates","buildMetadata","composeTitle","buildAutoFillMetaHook","buildRobots","buildSitemapEntries","createMetadataGenerator","createPageMetadata","injectAutoFillMeta","createLlmsTxtRoute","createManifestHandler","createSitemapRouteHandler","buildIconsMetadata","buildOrganizationJsonLd","validateFaviconField","buildNoindexField","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,EACfC,YAAY,EACZC,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,aAAa,QACR,6BAA4B;AAOnC,SACEC,gBAAgB,EAChBC,gBAAgB,EAChBC,cAAc,EACdC,iBAAiB,EACjBC,cAAc,EACdC,eAAe,EACfC,YAAY,QACP,6BAA4B;AAEnC,SAASC,YAAY,QAAQ,kCAAiC;AAE9D,SAASC,WAAW,QAAQ,iCAAgC;AAE5D,4EAA4E;AAC5E,gFAAgF;AAChF,gFAAgF;AAChF,SAASC,gBAAgB,QAAQ,sCAAqC;AAEtE,yEAAyE;AACzE,SAASC,SAAS,EAAEC,YAAY,QAAQ,yBAAwB;AAEhE,SAASC,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,8BAA6B;AAOnG,4EAA4E;AAC5E,+EAA+E;AAC/E,gCAAgC;AAChC,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,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B;AAC1D,SACEC,qBAAqB,EACrBC,yBAAyB,EACzBC,kBAAkB,QACb,yBAAwB;AAC/B,qFAAqF;AACrF,SACEC,cAAc,EACdC,wBAAwB,EACxBC,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 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 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'\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'\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'\nexport { buildCsp } from './modules/security/index.js'\n\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 { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js'\nexport type { AutoFillMapping, RobotsRules, SitemapEntry } 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","resolveRedirect","resolveRoute","searchContent","graphAdapter","mailAdapter","panelSmtpAdapter","assertEnv","ipalEnvRules","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","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","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,aAA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C7D,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SACEC,qBAAqB,EACrBC,yBAAyB,EACzBC,kBAAkB,QACb,yBAAwB;AAC/B,qFAAqF;AACrF,SACEC,cAAc,EACdC,wBAAwB,EACxBC,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 diff --git a/dist/modules/content/blocksToMarkdown.d.ts b/dist/modules/content/blocksToMarkdown.d.ts new file mode 100644 index 0000000..c26a70d --- /dev/null +++ b/dist/modules/content/blocksToMarkdown.d.ts @@ -0,0 +1,26 @@ +/** + * Converts a page's `blocks` layout to Markdown by CONVENTION — the same field + * names the project already standardises on (heading, subheading, body, + * content, image, items/faq/…; see the naming rules in agents.md). The plugin + * can't know each project's block shapes, but it CAN rely on those conventions, + * so most blocks convert with zero per-project wiring. Special blocks get an + * `overrides` entry keyed by blockType. + * + * Output is for AI/agent consumption (per-page Markdown, llms-full.txt), not + * on-page rendering — it extracts readable text, not pixel-perfect layout. + * + * blocksToMarkdown(page.layout) + * blocksToMarkdown(page.layout, { + * overrides: { gallery: (b) => `(${(b.images as unknown[])?.length ?? 0} photos)` }, + * }) + */ +type Block = Record & { + blockType?: string; +}; +type BlockToMarkdown = (block: Block) => string; +type BlocksToMarkdownArgs = { + /** Per-blockType custom renderers. Return '' to omit a block. */ + overrides?: Record; +}; +export declare function blocksToMarkdown(layout: unknown, args?: BlocksToMarkdownArgs): string; +export {}; diff --git a/dist/modules/content/blocksToMarkdown.js b/dist/modules/content/blocksToMarkdown.js new file mode 100644 index 0000000..21b1f0e --- /dev/null +++ b/dist/modules/content/blocksToMarkdown.js @@ -0,0 +1,102 @@ +// Import the leaf, not the richtext barrel — the barrel re-exports +// RenderRichText (a React component), which would pull React into this pure, +// server-usable module. +import { lexicalToMarkdown } from '../richtext/lexicalToMarkdown.js'; +const HEADING_KEYS = new Set([ + 'heading', + 'title' +]); +const SUBHEADING_KEYS = new Set([ + 'subheading', + 'subtitle' +]); +const QUESTION_KEYS = new Set([ + 'question' +]); +const TEXT_KEYS = new Set([ + 'body', + 'text', + 'description', + 'excerpt', + 'summary', + 'answer', + 'caption', + 'label', + 'content' +]); +const ARRAY_KEYS = new Set([ + 'items', + 'features', + 'faq', + 'faqs', + 'cards', + 'columns', + 'rows', + 'questions', + 'services', + 'steps', + 'points', + 'benefits', + 'list' +]); +/** A populated richText value is an object with a `root`. */ function isRichText(v) { + return !!v && typeof v === 'object' && 'root' in v; +} +/** A populated upload (image) is an object with a `url`. */ function imageMarkdown(v) { + if (!v || typeof v !== 'object') return ''; + const o = v; + const url = typeof o.url === 'string' ? o.url : ''; + const alt = typeof o.alt === 'string' ? o.alt : ''; + return url ? `![${alt}](${url})` : ''; +} +/** Extract readable Markdown from one block's known content fields. */ function extractBlock(block, depth) { + const lines = []; + for (const [key, value] of Object.entries(block)){ + if (value == null) continue; + if (HEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) { + lines.push(`## ${value.trim()}`); + } else if (SUBHEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) { + lines.push(`### ${value.trim()}`); + } else if (QUESTION_KEYS.has(key) && typeof value === 'string' && value.trim()) { + lines.push(`**${value.trim()}**`); + } else if (key === 'image') { + const img = imageMarkdown(value); + if (img) lines.push(img); + } else if (isRichText(value)) { + const md = lexicalToMarkdown(value); + if (md) lines.push(md); + } else if (TEXT_KEYS.has(key) && typeof value === 'string' && value.trim()) { + lines.push(value.trim()); + } else if (ARRAY_KEYS.has(key) && Array.isArray(value) && depth < 4) { + for (const item of value){ + if (item && typeof item === 'object') { + const sub = extractBlock(item, depth + 1); + if (sub.trim()) lines.push(sub); + } else if (typeof item === 'string' && item.trim()) { + lines.push(`- ${item.trim()}`); + } + } + } + } + return lines.join('\n\n'); +} +export function blocksToMarkdown(layout, args = {}) { + if (!Array.isArray(layout)) return ''; + const { overrides = {} } = args; + const out = []; + for (const block of layout){ + if (!block || typeof block !== 'object') continue; + const b = block; + const type = typeof b.blockType === 'string' ? b.blockType : ''; + if (type && overrides[type]) { + const md = overrides[type](b); + if (md.trim()) out.push(md.trim()); + continue; + } + const md = extractBlock(b, 0); + if (md.trim()) out.push(md.trim()); + } + return out.join('\n\n').trim(); +} + +//# sourceMappingURL=blocksToMarkdown.js.map \ No newline at end of file diff --git a/dist/modules/content/blocksToMarkdown.js.map b/dist/modules/content/blocksToMarkdown.js.map new file mode 100644 index 0000000..832a49d --- /dev/null +++ b/dist/modules/content/blocksToMarkdown.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/content/blocksToMarkdown.ts"],"sourcesContent":["// Import the leaf, not the richtext barrel — the barrel re-exports\n// RenderRichText (a React component), which would pull React into this pure,\n// server-usable module.\nimport { lexicalToMarkdown } from '../richtext/lexicalToMarkdown.js'\n\n/**\n * Converts a page's `blocks` layout to Markdown by CONVENTION — the same field\n * names the project already standardises on (heading, subheading, body,\n * content, image, items/faq/…; see the naming rules in agents.md). The plugin\n * can't know each project's block shapes, but it CAN rely on those conventions,\n * so most blocks convert with zero per-project wiring. Special blocks get an\n * `overrides` entry keyed by blockType.\n *\n * Output is for AI/agent consumption (per-page Markdown, llms-full.txt), not\n * on-page rendering — it extracts readable text, not pixel-perfect layout.\n *\n * blocksToMarkdown(page.layout)\n * blocksToMarkdown(page.layout, {\n * overrides: { gallery: (b) => `(${(b.images as unknown[])?.length ?? 0} photos)` },\n * })\n */\n\ntype Block = Record & { blockType?: string }\ntype BlockToMarkdown = (block: Block) => string\n\ntype BlocksToMarkdownArgs = {\n /** Per-blockType custom renderers. Return '' to omit a block. */\n overrides?: Record\n}\n\nconst HEADING_KEYS = new Set(['heading', 'title'])\nconst SUBHEADING_KEYS = new Set(['subheading', 'subtitle'])\nconst QUESTION_KEYS = new Set(['question'])\nconst TEXT_KEYS = new Set([\n 'body',\n 'text',\n 'description',\n 'excerpt',\n 'summary',\n 'answer',\n 'caption',\n 'label',\n 'content',\n])\nconst ARRAY_KEYS = new Set([\n 'items',\n 'features',\n 'faq',\n 'faqs',\n 'cards',\n 'columns',\n 'rows',\n 'questions',\n 'services',\n 'steps',\n 'points',\n 'benefits',\n 'list',\n])\n\n/** A populated richText value is an object with a `root`. */\nfunction isRichText(v: unknown): boolean {\n return !!v && typeof v === 'object' && 'root' in (v as Record)\n}\n\n/** A populated upload (image) is an object with a `url`. */\nfunction imageMarkdown(v: unknown): string {\n if (!v || typeof v !== 'object') return ''\n const o = v as Record\n const url = typeof o.url === 'string' ? o.url : ''\n const alt = typeof o.alt === 'string' ? o.alt : ''\n return url ? `![${alt}](${url})` : ''\n}\n\n/** Extract readable Markdown from one block's known content fields. */\nfunction extractBlock(block: Block, depth: number): string {\n const lines: string[] = []\n\n for (const [key, value] of Object.entries(block)) {\n if (value == null) continue\n\n if (HEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) {\n lines.push(`## ${value.trim()}`)\n } else if (SUBHEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) {\n lines.push(`### ${value.trim()}`)\n } else if (QUESTION_KEYS.has(key) && typeof value === 'string' && value.trim()) {\n lines.push(`**${value.trim()}**`)\n } else if (key === 'image') {\n const img = imageMarkdown(value)\n if (img) lines.push(img)\n } else if (isRichText(value)) {\n const md = lexicalToMarkdown(value as never)\n if (md) lines.push(md)\n } else if (TEXT_KEYS.has(key) && typeof value === 'string' && value.trim()) {\n lines.push(value.trim())\n } else if (ARRAY_KEYS.has(key) && Array.isArray(value) && depth < 4) {\n for (const item of value) {\n if (item && typeof item === 'object') {\n const sub = extractBlock(item as Block, depth + 1)\n if (sub.trim()) lines.push(sub)\n } else if (typeof item === 'string' && item.trim()) {\n lines.push(`- ${item.trim()}`)\n }\n }\n }\n }\n\n return lines.join('\\n\\n')\n}\n\nexport function blocksToMarkdown(layout: unknown, args: BlocksToMarkdownArgs = {}): string {\n if (!Array.isArray(layout)) return ''\n const { overrides = {} } = args\n const out: string[] = []\n\n for (const block of layout) {\n if (!block || typeof block !== 'object') continue\n const b = block as Block\n const type = typeof b.blockType === 'string' ? b.blockType : ''\n\n if (type && overrides[type]) {\n const md = overrides[type](b)\n if (md.trim()) out.push(md.trim())\n continue\n }\n\n const md = extractBlock(b, 0)\n if (md.trim()) out.push(md.trim())\n }\n\n return out.join('\\n\\n').trim()\n}\n"],"names":["lexicalToMarkdown","HEADING_KEYS","Set","SUBHEADING_KEYS","QUESTION_KEYS","TEXT_KEYS","ARRAY_KEYS","isRichText","v","imageMarkdown","o","url","alt","extractBlock","block","depth","lines","key","value","Object","entries","has","trim","push","img","md","Array","isArray","item","sub","join","blocksToMarkdown","layout","args","overrides","out","b","type","blockType"],"mappings":"AAAA,mEAAmE;AACnE,6EAA6E;AAC7E,wBAAwB;AACxB,SAASA,iBAAiB,QAAQ,mCAAkC;AA2BpE,MAAMC,eAAe,IAAIC,IAAI;IAAC;IAAW;CAAQ;AACjD,MAAMC,kBAAkB,IAAID,IAAI;IAAC;IAAc;CAAW;AAC1D,MAAME,gBAAgB,IAAIF,IAAI;IAAC;CAAW;AAC1C,MAAMG,YAAY,IAAIH,IAAI;IACxB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AACD,MAAMI,aAAa,IAAIJ,IAAI;IACzB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,2DAA2D,GAC3D,SAASK,WAAWC,CAAU;IAC5B,OAAO,CAAC,CAACA,KAAK,OAAOA,MAAM,YAAY,UAAWA;AACpD;AAEA,0DAA0D,GAC1D,SAASC,cAAcD,CAAU;IAC/B,IAAI,CAACA,KAAK,OAAOA,MAAM,UAAU,OAAO;IACxC,MAAME,IAAIF;IACV,MAAMG,MAAM,OAAOD,EAAEC,GA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MAAMC,OAAO,CAACT,UAAUH,QAAQ,GAAG;YACnE,KAAK,MAAMa,QAAQV,MAAO;gBACxB,IAAIU,QAAQ,OAAOA,SAAS,UAAU;oBACpC,MAAMC,MAAMhB,aAAae,MAAeb,QAAQ;oBAChD,IAAIc,IAAIP,IAAI,IAAIN,MAAMO,IAAI,CAACM;gBAC7B,OAAO,IAAI,OAAOD,SAAS,YAAYA,KAAKN,IAAI,IAAI;oBAClDN,MAAMO,IAAI,CAAC,CAAC,EAAE,EAAEK,KAAKN,IAAI,IAAI;gBAC/B;YACF;QACF;IACF;IAEA,OAAON,MAAMc,IAAI,CAAC;AACpB;AAEA,OAAO,SAASC,iBAAiBC,MAAe,EAAEC,OAA6B,CAAC,CAAC;IAC/E,IAAI,CAACP,MAAMC,OAAO,CAACK,SAAS,OAAO;IACnC,MAAM,EAAEE,YAAY,CAAC,CAAC,EAAE,GAAGD;IAC3B,MAAME,MAAgB,EAAE;IAExB,KAAK,MAAMrB,SAASkB,OAAQ;QAC1B,IAAI,CAAClB,SAAS,OAAOA,UAAU,UAAU;QACzC,MAAMsB,IAAItB;QACV,MAAMuB,OAAO,OAAOD,EAAEE,SAAS,KAAK,WAAWF,EAAEE,SAAS,GAAG;QAE7D,IAAID,QAAQH,SAAS,CAACG,KAAK,EAAE;YAC3B,MAAMZ,KAAKS,SAAS,CAACG,KAAK,CAACD;YAC3B,IAAIX,GAAGH,IAAI,IAAIa,IAAIZ,IAAI,CAACE,GAAGH,IAAI;YAC/B;QACF;QAEA,MAAMG,KAAKZ,aAAauB,GAAG;QAC3B,IAAIX,GAAGH,IAAI,IAAIa,IAAIZ,IAAI,CAACE,GAAGH,IAAI;IACjC;IAEA,OAAOa,IAAIL,IAAI,CAAC,QAAQR,IAAI;AAC9B"} \ No newline at end of file diff --git a/dist/modules/content/createMarkdownRenderer.d.ts b/dist/modules/content/createMarkdownRenderer.d.ts new file mode 100644 index 0000000..530ad68 --- /dev/null +++ b/dist/modules/content/createMarkdownRenderer.d.ts @@ -0,0 +1,52 @@ +import type { BasePayload } from 'payload'; +import type { ContentOption } from './types.js'; +type CreateMarkdownRendererArgs = { + /** Pages collection. Default 'pages'. */ + collection?: string; + /** Archive-backed collections, same value as the plugin option (optional). */ + content?: ContentOption; + /** Prepend a YAML frontmatter block (title/description/locale). Default true. */ + frontmatter?: boolean; + /** Field holding the block layout. Default 'layout'. */ + layoutField?: string; + /** Per-blockType overrides passed to blocksToMarkdown. */ + overrides?: Record) => string>; + /** SiteSettings global slug. Default 'site-settings'. */ + settingsSlug?: string; +}; +type MarkdownContext = { + locale: string; + payload: BasePayload; + /** Route slug segments; empty/undefined = locale root (home). */ + slug?: string[]; +}; +/** + * Returns a function that renders a page (or archive/entry) to clean Markdown — + * title, meta description, then the block layout via blocksToMarkdown. The + * point is AI-readability: an agent (Claude's WebFetch, GPT, Perplexity) gets + * structured Markdown instead of parsing HTML, so it reads the page reliably. + * + * Mirrors createPageMetadata: the plugin can't call getPayload, so it returns a + * function the project invokes from its route handler. + * + * // app/md/[locale]/[[...slug]]/route.ts (serves /md/pl/o-nas as text/markdown) + * import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit' + * import { getPayload } from 'payload' + * import config from '@payload-config' + * const render = createMarkdownRenderer({ content }) + * export const dynamic = 'force-dynamic' + * export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) { + * const { locale, slug } = await params + * const md = await render({ payload: await getPayload({ config }), locale, slug }) + * return markdownResponse(md) + * } + * + * Returns null when the route doesn't resolve (so the handler can 404). + */ +export declare function createMarkdownRenderer(args?: CreateMarkdownRendererArgs): ({ slug, locale, payload }: MarkdownContext) => Promise; +/** + * Wraps a Markdown string in a `text/markdown` Response, or a 404 when null. + * Uses the global Response — no next/server import. + */ +export declare function markdownResponse(md: null | string): Response; +export {}; diff --git a/dist/modules/content/createMarkdownRenderer.js b/dist/modules/content/createMarkdownRenderer.js new file mode 100644 index 0000000..8fe5d5d --- /dev/null +++ b/dist/modules/content/createMarkdownRenderer.js @@ -0,0 +1,97 @@ +import { blocksToMarkdown } from './blocksToMarkdown.js'; +import { resolveRoute } from './resolveRoute.js'; +function yamlEscape(v) { + return `"${v.replace(/"/g, '\\"')}"`; +} +/** + * Returns a function that renders a page (or archive/entry) to clean Markdown — + * title, meta description, then the block layout via blocksToMarkdown. The + * point is AI-readability: an agent (Claude's WebFetch, GPT, Perplexity) gets + * structured Markdown instead of parsing HTML, so it reads the page reliably. + * + * Mirrors createPageMetadata: the plugin can't call getPayload, so it returns a + * function the project invokes from its route handler. + * + * // app/md/[locale]/[[...slug]]/route.ts (serves /md/pl/o-nas as text/markdown) + * import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit' + * import { getPayload } from 'payload' + * import config from '@payload-config' + * const render = createMarkdownRenderer({ content }) + * export const dynamic = 'force-dynamic' + * export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) { + * const { locale, slug } = await params + * const md = await render({ payload: await getPayload({ config }), locale, slug }) + * return markdownResponse(md) + * } + * + * Returns null when the route doesn't resolve (so the handler can 404). + */ export function createMarkdownRenderer(args = {}) { + const { collection = 'pages', content, frontmatter = true, layoutField = 'layout', overrides, settingsSlug = 'site-settings' } = args; + return async function render({ slug, locale, payload }) { + const route = await resolveRoute({ + content, + locale, + pagesSlug: collection, + payload, + segments: slug, + settingsSlug + }); + if (!route) { + return null; + } + const doc = route.doc; + const title = typeof doc.title === 'string' ? doc.title : ''; + const description = typeof doc.meta?.description === 'string' ? doc.meta.description : ''; + const body = blocksToMarkdown(doc[layoutField], { + overrides + }); + const parts = []; + if (frontmatter) { + const fm = [ + '---', + `locale: ${locale}` + ]; + if (title) { + fm.push(`title: ${yamlEscape(title)}`); + } + if (description) { + fm.push(`description: ${yamlEscape(description)}`); + } + fm.push('---'); + parts.push(fm.join('\n')); + } + if (title) { + parts.push(`# ${title}`); + } + if (description) { + parts.push(`_${description}_`); + } + if (body) { + parts.push(body); + } + const md = parts.join('\n\n').trim(); + return md || null; + }; +} +/** + * Wraps a Markdown string in a `text/markdown` Response, or a 404 when null. + * Uses the global Response — no next/server import. + */ export function markdownResponse(md) { + if (md == null) { + return new Response('Not found', { + headers: { + 'content-type': 'text/plain' + }, + status: 404 + }); + } + return new Response(md, { + headers: { + 'cache-control': 'public, max-age=0, s-maxage=3600, stale-while-revalidate=86400', + 'content-type': 'text/markdown; charset=utf-8' + }, + status: 200 + }); +} + +//# sourceMappingURL=createMarkdownRenderer.js.map \ No newline at end of file diff --git a/dist/modules/content/createMarkdownRenderer.js.map b/dist/modules/content/createMarkdownRenderer.js.map new file mode 100644 index 0000000..fc8d496 --- /dev/null +++ b/dist/modules/content/createMarkdownRenderer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/content/createMarkdownRenderer.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { ContentOption } from './types.js'\n\nimport { blocksToMarkdown } from './blocksToMarkdown.js'\nimport { resolveRoute } from './resolveRoute.js'\n\ntype CreateMarkdownRendererArgs = {\n /** Pages collection. Default 'pages'. */\n collection?: string\n /** Archive-backed collections, same value as the plugin option (optional). */\n content?: ContentOption\n /** Prepend a YAML frontmatter block (title/description/locale). Default true. */\n frontmatter?: boolean\n /** Field holding the block layout. Default 'layout'. */\n layoutField?: string\n /** Per-blockType overrides passed to blocksToMarkdown. */\n overrides?: Record) => string>\n /** SiteSettings global slug. Default 'site-settings'. */\n settingsSlug?: string\n}\n\ntype MarkdownContext = {\n locale: string\n payload: BasePayload\n /** Route slug segments; empty/undefined = locale root (home). */\n slug?: string[]\n}\n\ntype DocShape = {\n [key: string]: unknown\n meta?: { description?: null | string } | null\n title?: null | string\n}\n\nfunction yamlEscape(v: string): string {\n return `\"${v.replace(/\"/g, '\\\\\"')}\"`\n}\n\n/**\n * Returns a function that renders a page (or archive/entry) to clean Markdown —\n * title, meta description, then the block layout via blocksToMarkdown. The\n * point is AI-readability: an agent (Claude's WebFetch, GPT, Perplexity) gets\n * structured Markdown instead of parsing HTML, so it reads the page reliably.\n *\n * Mirrors createPageMetadata: the plugin can't call getPayload, so it returns a\n * function the project invokes from its route handler.\n *\n * // app/md/[locale]/[[...slug]]/route.ts (serves /md/pl/o-nas as text/markdown)\n * import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit'\n * import { getPayload } from 'payload'\n * import config from '@payload-config'\n * const render = createMarkdownRenderer({ content })\n * export const dynamic = 'force-dynamic'\n * export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) {\n * const { locale, slug } = await params\n * const md = await render({ payload: await getPayload({ config }), locale, slug })\n * return markdownResponse(md)\n * }\n *\n * Returns null when the route doesn't resolve (so the handler can 404).\n */\nexport function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) {\n const {\n collection = 'pages',\n content,\n frontmatter = true,\n layoutField = 'layout',\n overrides,\n settingsSlug = 'site-settings',\n } = args\n\n return async function render({ slug, locale, payload }: MarkdownContext): Promise {\n const route = await resolveRoute({\n content,\n locale,\n pagesSlug: collection,\n payload,\n segments: slug,\n settingsSlug,\n })\n if (!route) {return null}\n\n const doc = route.doc as DocShape\n const title = typeof doc.title === 'string' ? doc.title : ''\n const description = typeof doc.meta?.description === 'string' ? doc.meta.description : ''\n const body = blocksToMarkdown(doc[layoutField], { overrides })\n\n const parts: string[] = []\n\n if (frontmatter) {\n const fm = ['---', `locale: ${locale}`]\n if (title) {fm.push(`title: ${yamlEscape(title)}`)}\n if (description) {fm.push(`description: ${yamlEscape(description)}`)}\n fm.push('---')\n parts.push(fm.join('\\n'))\n }\n\n if (title) {parts.push(`# ${title}`)}\n if (description) {parts.push(`_${description}_`)}\n if (body) {parts.push(body)}\n\n const md = parts.join('\\n\\n').trim()\n return md || null\n }\n}\n\n/**\n * Wraps a Markdown string in a `text/markdown` Response, or a 404 when null.\n * Uses the global Response — no next/server import.\n */\nexport function markdownResponse(md: null | string): Response {\n if (md == null) {\n return new Response('Not found', { headers: { 'content-type': 'text/plain' }, status: 404 })\n }\n return new Response(md, {\n headers: {\n 'cache-control': 'public, max-age=0, s-maxage=3600, stale-while-revalidate=86400',\n 'content-type': 'text/markdown; charset=utf-8',\n },\n status: 200,\n })\n}\n"],"names":["blocksToMarkdown","resolveRoute","yamlEscape","v","replace","createMarkdownRenderer","args","collection","content","frontmatter","layoutField","overrides","settingsSlug","render","slug","locale","payload","route","pagesSlug","segments","doc","title","description","meta","body","parts","fm","push","join","md","trim","markdownResponse","Response","headers","status"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,YAAY,QAAQ,oBAAmB;AA8BhD,SAASC,WAAWC,CAAS;IAC3B,OAAO,CAAC,CAAC,EAAEA,EAAEC,OAAO,CAAC,MAAM,OAAO,CAAC,CAAC;AACtC;AAEA;;;;;;;;;;;;;;;;;;;;;;CAsBC,GACD,OAAO,SAASC,uBAAuBC,OAAmC,CAAC,CAAC;IAC1E,MAAM,EACJC,aAAa,OAAO,EACpBC,OAAO,EACPC,cAAc,IAAI,EAClBC,cAAc,QAAQ,EACtBC,SAAS,EACTC,eAAe,eAAe,EAC/B,GAAGN;IAEJ,OAAO,eAAeO,OAAO,EAAEC,IAAI,EAAEC,MAAM,EAAEC,OAAO,EAAmB;QACrE,MAAMC,QAAQ,MAAMhB,aAAa;YAC/BO;YACAO;YACAG,WAAWX;YACXS;YACAG,UAAUL;YACVF;QACF;QACA,IAAI,CAACK,OAAO;YAAC,OAAO;QAAI;QAExB,MAAMG,MAAMH,MAAMG,GAAG;QACrB,MAAMC,QAAQ,OAAOD,IAAIC,KAAK,KAAK,WAAWD,IAAIC,KAAK,GAAG;QAC1D,MAAMC,cAAc,OAAOF,IAAIG,IAAI,EAAED,gBAAgB,WAAWF,IAAIG,IAAI,CAACD,WAAW,GAAG;QACvF,MAAME,OAAOxB,iBAAiBoB,GAAG,CAACV,YAAY,EAAE;YAAEC;QAAU;QAE5D,MAAMc,QAAkB,EAAE;QAE1B,IAAIhB,aAAa;YACf,MAAMiB,KAAK;gBAAC;gBAAO,CAAC,QAAQ,EAAEX,QAAQ;aAAC;YACvC,IAAIM,OAAO;gBAACK,GAAGC,IAAI,CAAC,CAAC,OAAO,EAAEzB,WAAWmB,QAAQ;YAAC;YAClD,IAAIC,aAAa;gBAACI,GAAGC,IAAI,CAAC,CAAC,aAAa,EAAEzB,WAAWoB,cAAc;YAAC;YACpEI,GAAGC,IAAI,CAAC;YACRF,MAAME,IAAI,CAACD,GAAGE,IAAI,CAAC;QACrB;QAEA,IAAIP,OAAO;YAACI,MAAME,IAAI,CAAC,CAAC,EAAE,EAAEN,OAAO;QAAC;QACpC,IAAIC,aAAa;YAACG,MAAME,IAAI,CAAC,CAAC,CAAC,EAAEL,YAAY,CAAC,CAAC;QAAC;QAChD,IAAIE,MAAM;YAACC,MAAME,IAAI,CAACH;QAAK;QAE3B,MAAMK,KAAKJ,MAAMG,IAAI,CAAC,QAAQE,IAAI;QAClC,OAAOD,MAAM;IACf;AACF;AAEA;;;CAGC,GACD,OAAO,SAASE,iBAAiBF,EAAiB;IAChD,IAAIA,MAAM,MAAM;QACd,OAAO,IAAIG,SAAS,aAAa;YAAEC,SAAS;gBAAE,gBAAgB;YAAa;YAAGC,QAAQ;QAAI;IAC5F;IACA,OAAO,IAAIF,SAASH,IAAI;QACtBI,SAAS;YACP,iBAAiB;YACjB,gBAAgB;QAClB;QACAC,QAAQ;IACV;AACF"} \ No newline at end of file diff --git a/dist/modules/content/createSearchRoute.d.ts b/dist/modules/content/createSearchRoute.d.ts new file mode 100644 index 0000000..4383025 --- /dev/null +++ b/dist/modules/content/createSearchRoute.d.ts @@ -0,0 +1,36 @@ +import type { BasePayload } from 'payload'; +import type { I18nConfig } from '../i18n/index.js'; +type CreateSearchRouteArgs = { + /** Absolute origin to prefix result URLs with. */ + baseUrl?: string; + /** Pages collection. Default 'pages'. */ + collection?: string; + config: I18nConfig; + /** Default result cap when ?limit is absent. Default 10. */ + defaultLimit?: number; + getCachedPayload: () => Promise; + /** Home slug map/string so the home result collapses to root. */ + homeSlug?: Record | string; + /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */ + summaryField?: string; +}; +/** + * A JSON content-search endpoint. Powers both the site's own search UI and + * external agents — one ranking, one source of truth (shares searchContent with + * the MCP server's search_content tool). + * + * // app/api/search/route.ts + * import { createSearchRoute } from '@intecion/ipal-kit' + * import { getCachedPayload } from '@/lib/content' + * import { i18nConfig } from '@/i18n.config' + * export const dynamic = 'force-dynamic' + * export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig, + * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! }) + * + * Query params: `q` (required), `locale`, `limit`. Response: + * { query, locale, count, results: [{ title, url, description?, slug }] } + * + * Uses the global Request/Response — no next/server import. + */ +export declare function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise; +export {}; diff --git a/dist/modules/content/createSearchRoute.js b/dist/modules/content/createSearchRoute.js new file mode 100644 index 0000000..9d6b04e --- /dev/null +++ b/dist/modules/content/createSearchRoute.js @@ -0,0 +1,80 @@ +import { searchContent } from './searchContent.js'; +/** + * A JSON content-search endpoint. Powers both the site's own search UI and + * external agents — one ranking, one source of truth (shares searchContent with + * the MCP server's search_content tool). + * + * // app/api/search/route.ts + * import { createSearchRoute } from '@intecion/ipal-kit' + * import { getCachedPayload } from '@/lib/content' + * import { i18nConfig } from '@/i18n.config' + * export const dynamic = 'force-dynamic' + * export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig, + * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! }) + * + * Query params: `q` (required), `locale`, `limit`. Response: + * { query, locale, count, results: [{ title, url, description?, slug }] } + * + * Uses the global Request/Response — no next/server import. + */ export function createSearchRoute(args) { + const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, summaryField } = args; + return async (req)=>{ + const url = new URL(req.url); + const query = url.searchParams.get('q')?.trim() ?? ''; + const locale = url.searchParams.get('locale') ?? undefined; + const limitParam = url.searchParams.get('limit'); + const limit = limitParam ? Number(limitParam) : defaultLimit; + if (!query) { + return Response.json({ + count: 0, + error: 'Missing ?q', + query: '', + results: [] + }, { + headers: { + 'cache-control': 'no-store' + }, + status: 400 + }); + } + try { + const payload = await getCachedPayload(); + const results = await searchContent({ + baseUrl, + collection, + config, + homeSlug, + limit, + locale, + payload, + query, + summaryField + }); + return Response.json({ + count: results.length, + locale: locale ?? config.defaultLocale, + query, + results + }, { + headers: { + 'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600' + } + }); + } catch (err) { + // DB unreachable (build) or unexpected — empty result rather than 500. + console.warn('[ipal] createSearchRoute: search failed:', err); + return Response.json({ + count: 0, + query, + results: [] + }, { + headers: { + 'cache-control': 'no-store' + }, + status: 200 + }); + } + }; +} + +//# sourceMappingURL=createSearchRoute.js.map \ No newline at end of file diff --git a/dist/modules/content/createSearchRoute.js.map b/dist/modules/content/createSearchRoute.js.map new file mode 100644 index 0000000..3c56a59 --- /dev/null +++ b/dist/modules/content/createSearchRoute.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/content/createSearchRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { searchContent } from './searchContent.js'\n\ntype CreateSearchRouteArgs = {\n /** Absolute origin to prefix result URLs with. */\n baseUrl?: string\n /** Pages collection. Default 'pages'. */\n collection?: string\n config: I18nConfig\n /** Default result cap when ?limit is absent. Default 10. */\n defaultLimit?: number\n getCachedPayload: () => Promise\n /** Home slug map/string so the home result collapses to root. */\n homeSlug?: Record | string\n /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */\n summaryField?: string\n}\n\n/**\n * A JSON content-search endpoint. Powers both the site's own search UI and\n * external agents — one ranking, one source of truth (shares searchContent with\n * the MCP server's search_content tool).\n *\n * // app/api/search/route.ts\n * import { createSearchRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })\n *\n * Query params: `q` (required), `locale`, `limit`. Response:\n * { query, locale, count, results: [{ title, url, description?, slug }] }\n *\n * Uses the global Request/Response — no next/server import.\n */\nexport function createSearchRoute(\n args: CreateSearchRouteArgs,\n): (req: Request) => Promise {\n const {\n baseUrl,\n collection = 'pages',\n config,\n defaultLimit = 10,\n getCachedPayload,\n homeSlug,\n summaryField,\n } = args\n\n return async (req: Request) => {\n const url = new URL(req.url)\n const query = url.searchParams.get('q')?.trim() ?? ''\n const locale = url.searchParams.get('locale') ?? undefined\n const limitParam = url.searchParams.get('limit')\n const limit = limitParam ? Number(limitParam) : defaultLimit\n\n if (!query) {\n return Response.json(\n { count: 0, error: 'Missing ?q', query: '', results: [] },\n { headers: { 'cache-control': 'no-store' }, status: 400 },\n )\n }\n\n try {\n const payload = await getCachedPayload()\n const results = await searchContent({\n baseUrl,\n collection,\n config,\n homeSlug,\n limit,\n locale,\n payload,\n query,\n summaryField,\n })\n return Response.json(\n { count: results.length, locale: locale ?? config.defaultLocale, query, results },\n {\n headers: {\n 'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600',\n },\n },\n )\n } catch (err) {\n // DB unreachable (build) or unexpected — empty result rather than 500.\n console.warn('[ipal] createSearchRoute: search failed:', err)\n return Response.json(\n { count: 0, query, results: [] },\n { headers: { 'cache-control': 'no-store' }, status: 200 },\n )\n }\n }\n}\n"],"names":["searchContent","createSearchRoute","args","baseUrl","collection","config","defaultLimit","getCachedPayload","homeSlug","summaryField","req","url","URL","query","searchParams","get","trim","locale","undefined","limitParam","limit","Number","Response","json","count","error","results","headers","status","payload","length","defaultLocale","err","console","warn"],"mappings":"AAIA,SAASA,aAAa,QAAQ,qBAAoB;AAiBlD;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASC,kBACdC,IAA2B;IAE3B,MAAM,EACJC,OAAO,EACPC,aAAa,OAAO,EACpBC,MAAM,EACNC,eAAe,EAAE,EACjBC,gBAAgB,EAChBC,QAAQ,EACRC,YAAY,EACb,GAAGP;IAEJ,OAAO,OAAOQ;QACZ,MAAMC,MAAM,IAAIC,IAAIF,IAAIC,GAAG;QAC3B,MAAME,QAAQF,IAAIG,YAAY,CAACC,GAAG,CAAC,MAAMC,UAAU;QACnD,MAAMC,SAASN,IAAIG,YAAY,CAACC,GAAG,CAAC,aAAaG;QACjD,MAAMC,aAAaR,IAAIG,YAAY,CAACC,GAAG,CAAC;QACxC,MAAMK,QAAQD,aAAaE,OAAOF,cAAcb;QAEhD,IAAI,CAACO,OAAO;YACV,OAAOS,SAASC,IAAI,CAClB;gBAAEC,OAAO;gBAAGC,OAAO;gBAAcZ,OAAO;gBAAIa,SAAS,EAAE;YAAC,GACxD;gBAAEC,SAAS;oBAAE,iBAAiB;gBAAW;gBAAGC,QAAQ;YAAI;QAE5D;QAEA,IAAI;YACF,MAAMC,UAAU,MAAMtB;YACtB,MAAMmB,UAAU,MAAM1B,cAAc;gBAClCG;gBACAC;gBACAC;gBACAG;gBACAY;gBACAH;gBACAY;gBACAhB;gBACAJ;YACF;YACA,OAAOa,SAASC,IAAI,CAClB;gBAAEC,OAAOE,QAAQI,MAAM;gBAAEb,QAAQA,UAAUZ,OAAO0B,aAAa;gBAAElB;gBAAOa;YAAQ,GAChF;gBACEC,SAAS;oBACP,iBAAiB;gBACnB;YACF;QAEJ,EAAE,OAAOK,KAAK;YACZ,uEAAuE;YACvEC,QAAQC,IAAI,CAAC,4CAA4CF;YACzD,OAAOV,SAASC,IAAI,CAClB;gBAAEC,OAAO;gBAAGX;gBAAOa,SAAS,EAAE;YAAC,GAC/B;gBAAEC,SAAS;oBAAE,iBAAiB;gBAAW;gBAAGC,QAAQ;YAAI;QAE5D;IACF;AACF"} \ No newline at end of file diff --git a/dist/modules/content/index.d.ts b/dist/modules/content/index.d.ts index 9706e0e..564819b 100644 --- a/dist/modules/content/index.d.ts +++ b/dist/modules/content/index.d.ts @@ -1,9 +1,15 @@ export { buildArchiveFields } from './archiveFields.js'; +export { blocksToMarkdown } from './blocksToMarkdown.js'; +export { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'; +export { createSearchRoute } from './createSearchRoute.js'; export { getArchiveEntries } from './getArchiveEntries.js'; export type { ArchiveEntries } from './getArchiveEntries.js'; +export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'; export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'; export { resolveRedirect } from './resolveRedirect.js'; export { resolveRoute } from './resolveRoute.js'; export type { ResolvedRoute } from './resolveRoute.js'; +export { searchContent } from './searchContent.js'; +export type { SearchResult } from './searchContent.js'; export type { ContentCollectionOption, ContentOption } from './types.js'; export { archiveFieldName } from './types.js'; diff --git a/dist/modules/content/index.js b/dist/modules/content/index.js index 8eccba0..5362f45 100644 --- a/dist/modules/content/index.js +++ b/dist/modules/content/index.js @@ -1,8 +1,13 @@ export { buildArchiveFields } from './archiveFields.js'; +export { blocksToMarkdown } from './blocksToMarkdown.js'; +export { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'; +export { createSearchRoute } from './createSearchRoute.js'; export { getArchiveEntries } from './getArchiveEntries.js'; +export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'; export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'; export { resolveRedirect } from './resolveRedirect.js'; export { resolveRoute } from './resolveRoute.js'; +export { searchContent } from './searchContent.js'; export { archiveFieldName } from './types.js'; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/modules/content/index.js.map b/dist/modules/content/index.js.map index 653b3b7..cb7c89d 100644 --- a/dist/modules/content/index.js.map +++ b/dist/modules/content/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveRedirect } from './resolveRedirect.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","getArchiveEntries","buildArchivePath","buildEntryPath","parsePageParam","resolveRedirect","resolveRoute","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAGhD,SAASC,gBAAgB,QAAQ,aAAY"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { blocksToMarkdown } from './blocksToMarkdown.js'\nexport { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'\nexport { createSearchRoute } from './createSearchRoute.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveRedirect } from './resolveRedirect.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport { searchContent } from './searchContent.js'\nexport type { SearchResult } from './searchContent.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","blocksToMarkdown","createMarkdownRenderer","markdownResponse","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","prefersMarkdown","buildArchivePath","buildEntryPath","parsePageParam","resolveRedirect","resolveRoute","searchContent","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,8BAA6B;AACtF,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,eAAe,EAAEC,YAAY,EAAEC,eAAe,QAAQ,2BAA0B;AACzF,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,aAAa,QAAQ,qBAAoB;AAGlD,SAASC,gBAAgB,QAAQ,aAAY"} \ No newline at end of file diff --git a/dist/modules/content/markdownNegotiation.d.ts b/dist/modules/content/markdownNegotiation.d.ts new file mode 100644 index 0000000..63e8ab0 --- /dev/null +++ b/dist/modules/content/markdownNegotiation.d.ts @@ -0,0 +1,38 @@ +/** + * Helpers for making the per-page Markdown (createMarkdownRenderer) discoverable + * and negotiable, so AI agents reliably find and read it. + * + * Two mechanisms: + * - `markdownHref` — the `` href a + * page advertises, so an agent fetching the HTML sees there's a Markdown + * version and can switch to it. + * - `prefersMarkdown` — reads the Accept header, so the same URL can serve + * Markdown when asked (content negotiation via a proxy rewrite). + */ +/** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */ +export declare const MARKDOWN_PREFIX = "/md"; +/** + * The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so + * the discovery link and the route agree. + * + * markdownHref('/pl/o-nas') // '/md/pl/o-nas' + * markdownHref('/pl/o-nas', '/ai') // '/ai/pl/o-nas' + * + * Advertise it from Next metadata so every page's points to its Markdown: + * + * // generateMetadata + * return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } } + */ +export declare function markdownHref(pathname: string, prefix?: string): string; +/** + * True when the client asked for Markdown via the Accept header (q-values + * respected: a higher-weighted text/html wins). Accepts a header string, a + * Headers object, or a Request. Use it in proxy.ts to serve the same URL as + * Markdown when an agent negotiates for it: + * + * // proxy.ts + * if (prefersMarkdown(request)) { + * return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url)) + * } + */ +export declare function prefersMarkdown(input: Headers | null | Request | string | undefined): boolean; diff --git a/dist/modules/content/markdownNegotiation.js b/dist/modules/content/markdownNegotiation.js new file mode 100644 index 0000000..7455493 --- /dev/null +++ b/dist/modules/content/markdownNegotiation.js @@ -0,0 +1,72 @@ +/** + * Helpers for making the per-page Markdown (createMarkdownRenderer) discoverable + * and negotiable, so AI agents reliably find and read it. + * + * Two mechanisms: + * - `markdownHref` — the `` href a + * page advertises, so an agent fetching the HTML sees there's a Markdown + * version and can switch to it. + * - `prefersMarkdown` — reads the Accept header, so the same URL can serve + * Markdown when asked (content negotiation via a proxy rewrite). + */ /** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */ export const MARKDOWN_PREFIX = '/md'; +/** + * The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so + * the discovery link and the route agree. + * + * markdownHref('/pl/o-nas') // '/md/pl/o-nas' + * markdownHref('/pl/o-nas', '/ai') // '/ai/pl/o-nas' + * + * Advertise it from Next metadata so every page's points to its Markdown: + * + * // generateMetadata + * return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } } + */ export function markdownHref(pathname, prefix = MARKDOWN_PREFIX) { + const clean = pathname.startsWith('/') ? pathname : `/${pathname}`; + const p = prefix.replace(/\/$/, ''); + return `${p}${clean === '/' ? '' : clean}` || p; +} +/** + * True when the client asked for Markdown via the Accept header (q-values + * respected: a higher-weighted text/html wins). Accepts a header string, a + * Headers object, or a Request. Use it in proxy.ts to serve the same URL as + * Markdown when an agent negotiates for it: + * + * // proxy.ts + * if (prefersMarkdown(request)) { + * return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url)) + * } + */ export function prefersMarkdown(input) { + let accept = null; + if (!input) { + return false; + } + if (typeof input === 'string') { + accept = input; + } else if (input instanceof Headers) { + accept = input.get('accept'); + } else if ('headers' in input && input.headers) { + accept = input.headers.get('accept'); + } + if (!accept) { + return false; + } + // Parse "type/subtype;q=0.8" entries into {type, q}. + const entries = accept.split(',').map((part)=>{ + const [type, ...params] = part.trim().split(';'); + const qParam = params.find((p)=>p.trim().startsWith('q=')); + const q = qParam ? Number(qParam.split('=')[1]) : 1; + return { + type: type.trim().toLowerCase(), + q: Number.isFinite(q) ? q : 1 + }; + }); + const md = entries.find((e)=>e.type === 'text/markdown'); + if (!md) { + return false; + } + // Markdown must be at least as preferred as html (and html not strictly higher). + const html = entries.find((e)=>e.type === 'text/html'); + return !html || md.q >= html.q; +} + +//# sourceMappingURL=markdownNegotiation.js.map \ No newline at end of file diff --git a/dist/modules/content/markdownNegotiation.js.map b/dist/modules/content/markdownNegotiation.js.map new file mode 100644 index 0000000..e9cc5e7 --- /dev/null +++ b/dist/modules/content/markdownNegotiation.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/content/markdownNegotiation.ts"],"sourcesContent":["/**\n * Helpers for making the per-page Markdown (createMarkdownRenderer) discoverable\n * and negotiable, so AI agents reliably find and read it.\n *\n * Two mechanisms:\n * - `markdownHref` — the `` href a\n * page advertises, so an agent fetching the HTML sees there's a Markdown\n * version and can switch to it.\n * - `prefersMarkdown` — reads the Accept header, so the same URL can serve\n * Markdown when asked (content negotiation via a proxy rewrite).\n */\n\n/** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */\nexport const MARKDOWN_PREFIX = '/md'\n\n/**\n * The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so\n * the discovery link and the route agree.\n *\n * markdownHref('/pl/o-nas') // '/md/pl/o-nas'\n * markdownHref('/pl/o-nas', '/ai') // '/ai/pl/o-nas'\n *\n * Advertise it from Next metadata so every page's points to its Markdown:\n *\n * // generateMetadata\n * return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } }\n */\nexport function markdownHref(pathname: string, prefix: string = MARKDOWN_PREFIX): string {\n const clean = pathname.startsWith('/') ? pathname : `/${pathname}`\n const p = prefix.replace(/\\/$/, '')\n return `${p}${clean === '/' ? '' : clean}` || p\n}\n\n/**\n * True when the client asked for Markdown via the Accept header (q-values\n * respected: a higher-weighted text/html wins). Accepts a header string, a\n * Headers object, or a Request. Use it in proxy.ts to serve the same URL as\n * Markdown when an agent negotiates for it:\n *\n * // proxy.ts\n * if (prefersMarkdown(request)) {\n * return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url))\n * }\n */\nexport function prefersMarkdown(input: Headers | null | Request | string | undefined): boolean {\n let accept: null | string = null\n if (!input) {return false}\n if (typeof input === 'string') {accept = input}\n else if (input instanceof Headers) {accept = input.get('accept')}\n else if ('headers' in input && input.headers) {accept = input.headers.get('accept')}\n if (!accept) {return false}\n\n // Parse \"type/subtype;q=0.8\" entries into {type, q}.\n const entries = accept.split(',').map((part) => {\n const [type, ...params] = part.trim().split(';')\n const qParam = params.find((p) => p.trim().startsWith('q='))\n const q = qParam ? Number(qParam.split('=')[1]) : 1\n return { type: type.trim().toLowerCase(), q: Number.isFinite(q) ? q : 1 }\n })\n\n const md = entries.find((e) => e.type === 'text/markdown')\n if (!md) {return false}\n // Markdown must be at least as preferred as html (and html not strictly higher).\n const html = entries.find((e) => e.type === 'text/html')\n return !html || md.q >= html.q\n}\n"],"names":["MARKDOWN_PREFIX","markdownHref","pathname","prefix","clean","startsWith","p","replace","prefersMarkdown","input","accept","Headers","get","headers","entries","split","map","part","type","params","trim","qParam","find","q","Number","toLowerCase","isFinite","md","e","html"],"mappings":"AAAA;;;;;;;;;;CAUC,GAED,sFAAsF,GACtF,OAAO,MAAMA,kBAAkB,MAAK;AAEpC;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,aAAaC,QAAgB,EAAEC,SAAi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QAAQF,GAAGJ,CAAC,IAAIM,KAAKN,CAAC;AAChC"} \ No newline at end of file diff --git a/dist/modules/content/searchContent.d.ts b/dist/modules/content/searchContent.d.ts new file mode 100644 index 0000000..98668cc --- /dev/null +++ b/dist/modules/content/searchContent.d.ts @@ -0,0 +1,43 @@ +import type { BasePayload } from 'payload'; +import type { I18nConfig } from '../i18n/index.js'; +export type SearchResult = { + description?: string; + slug: string; + title: string; + /** Locale-aware path, prefixed with baseUrl when given. */ + url: string; +}; +type SearchContentArgs = { + /** Absolute origin to prefix URLs with. Omit for relative paths. */ + baseUrl?: string; + /** Pages collection. Default 'pages'. */ + collection?: string; + config: I18nConfig; + /** Home slug map/string so the home result collapses to root. */ + homeSlug?: Record | string; + /** Max results. Default 10, clamped 1–50. */ + limit?: number; + /** Locale to search/return. Defaults to config.defaultLocale; invalid → default. */ + locale?: string; + payload: BasePayload; + /** Keywords. */ + query: string; + /** + * Field holding a richer AI summary (see buildSummaryField). When set and + * present on a doc, it's preferred over meta.description for the result's + * description. + */ + summaryField?: string; +}; +/** + * Shared content search: title / meta-description keyword match over a + * collection, returning structured results (published, non-noindex only). One + * implementation behind BOTH the JSON search route (createSearchRoute) and the + * MCP server's search_content tool — so site search, API and AI all rank the + * same way. + * + * Degrades to [] (never throws) when the collection's fields aren't queryable — + * same guard class as the drafts/_status lesson. + */ +export declare function searchContent({ baseUrl, collection, config, homeSlug, limit, locale, payload, query, summaryField, }: SearchContentArgs): Promise; +export {}; diff --git a/dist/modules/content/searchContent.js b/dist/modules/content/searchContent.js new file mode 100644 index 0000000..f2b8e70 --- /dev/null +++ b/dist/modules/content/searchContent.js @@ -0,0 +1,84 @@ +import { buildLocalizedPath, getDefaultLocale, isValidLocale } from '../i18n/index.js'; +/** + * Shared content search: title / meta-description keyword match over a + * collection, returning structured results (published, non-noindex only). One + * implementation behind BOTH the JSON search route (createSearchRoute) and the + * MCP server's search_content tool — so site search, API and AI all rank the + * same way. + * + * Degrades to [] (never throws) when the collection's fields aren't queryable — + * same guard class as the drafts/_status lesson. + */ export async function searchContent({ baseUrl, collection = 'pages', config, homeSlug, limit = 10, locale, payload, query, summaryField }) { + const q = query.trim(); + if (!q) { + return []; + } + const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config); + const max = Math.min(Math.max(Math.trunc(limit) || 10, 1), 50); + const origin = baseUrl?.replace(/\/$/, '') ?? ''; + let docs = []; + try { + const res = await payload.find({ + collection: collection, + depth: 0, + limit: max * 3, + locale: loc, + where: { + or: [ + { + title: { + like: q + } + }, + { + 'meta.description': { + like: q + } + } + ] + } + }); + docs = res?.docs ?? []; + } catch { + return []; + } + const results = []; + for (const doc of docs){ + if (doc._status && doc._status !== 'published') { + continue; + } + if (doc.meta?.noindex) { + continue; + } + const title = typeof doc.title === 'string' ? doc.title : undefined; + const slug = typeof doc.slug === 'string' ? doc.slug : undefined; + if (!title || !slug) { + continue; + } + const path = buildLocalizedPath({ + config, + homeSlug, + locale: loc, + slugs: { + [loc]: slug + } + }); + // Prefer the richer AI summary when configured and present, else meta.description. + const summary = summaryField && typeof doc[summaryField] === 'string' ? doc[summaryField] : undefined; + const description = summary?.trim() || (typeof doc.meta?.description === 'string' ? doc.meta.description : undefined); + results.push({ + slug, + title, + url: `${origin}${path ?? `/${slug}`}`, + ...description ? { + description + } : {} + }); + if (results.length >= max) { + break; + } + } + return results; +} + +//# sourceMappingURL=searchContent.js.map \ No newline at end of file diff --git a/dist/modules/content/searchContent.js.map b/dist/modules/content/searchContent.js.map new file mode 100644 index 0000000..1584e29 --- /dev/null +++ b/dist/modules/content/searchContent.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/content/searchContent.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { buildLocalizedPath, getDefaultLocale, isValidLocale } from '../i18n/index.js'\n\nexport type SearchResult = {\n description?: string\n slug: string\n title: string\n /** Locale-aware path, prefixed with baseUrl when given. */\n url: string\n}\n\ntype SearchContentArgs = {\n /** Absolute origin to prefix URLs with. Omit for relative paths. */\n baseUrl?: string\n /** Pages collection. Default 'pages'. */\n collection?: string\n config: I18nConfig\n /** Home slug map/string so the home result collapses to root. */\n homeSlug?: Record | string\n /** Max results. Default 10, clamped 1–50. */\n limit?: number\n /** Locale to search/return. Defaults to config.defaultLocale; invalid → default. */\n locale?: string\n payload: BasePayload\n /** Keywords. */\n query: string\n /**\n * Field holding a richer AI summary (see buildSummaryField). When set and\n * present on a doc, it's preferred over meta.description for the result's\n * description.\n */\n summaryField?: string\n}\n\ntype PageRow = {\n [key: string]: unknown\n _status?: string\n id: number | string\n meta?: { description?: unknown; noindex?: boolean } | null\n slug?: unknown\n title?: unknown\n}\n\n/**\n * Shared content search: title / meta-description keyword match over a\n * collection, returning structured results (published, non-noindex only). One\n * implementation behind BOTH the JSON search route (createSearchRoute) and the\n * MCP server's search_content tool — so site search, API and AI all rank the\n * same way.\n *\n * Degrades to [] (never throws) when the collection's fields aren't queryable —\n * same guard class as the drafts/_status lesson.\n */\nexport async function searchContent({\n baseUrl,\n collection = 'pages',\n config,\n homeSlug,\n limit = 10,\n locale,\n payload,\n query,\n summaryField,\n}: SearchContentArgs): Promise {\n const q = query.trim()\n if (!q) {return []}\n\n const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config)\n const max = Math.min(Math.max(Math.trunc(limit) || 10, 1), 50)\n const origin = baseUrl?.replace(/\\/$/, '') ?? ''\n\n let docs: PageRow[] = []\n try {\n const res = await payload.find({\n collection: collection as never,\n depth: 0,\n limit: max * 3, // over-fetch; drafts/noindex filtered in memory\n locale: loc as never,\n where: {\n or: [{ title: { like: q } }, { 'meta.description': { like: q } }],\n } as never,\n })\n docs = (res?.docs ?? []) as PageRow[]\n } catch {\n return []\n }\n\n const results: SearchResult[] = []\n for (const doc of docs) {\n if (doc._status && doc._status !== 'published') {continue}\n if (doc.meta?.noindex) {continue}\n const title = typeof doc.title === 'string' ? doc.title : undefined\n const slug = typeof doc.slug === 'string' ? doc.slug : undefined\n if (!title || !slug) {continue}\n const path = buildLocalizedPath({ config, homeSlug, locale: loc, slugs: { [loc]: slug } })\n // Prefer the richer AI summary when configured and present, else meta.description.\n const summary =\n summaryField && typeof doc[summaryField] === 'string'\n ? (doc[summaryField])\n : undefined\n const description =\n summary?.trim() ||\n (typeof doc.meta?.description === 'string' ? doc.meta.description : undefined)\n results.push({\n slug,\n title,\n url: `${origin}${path ?? `/${slug}`}`,\n ...(description ? { description } : {}),\n })\n if (results.length >= max) {break}\n }\n\n return results\n}\n"],"names":["buildLocalizedPath","getDefaultLocale","isValidLocale","searchContent","baseUrl","collection","config","homeSlug","limit","locale","payload","query","summaryField","q","trim","loc","max","Math","min","trunc","origin","replace","docs","res","find","depth","where","or","title","like","results","doc","_status","meta","noindex","undefined","slug","path","slugs","summary","description","push","url","length"],"mappings":"AAIA,SAASA,kBAAkB,EAAEC,gBAAgB,EAAEC,aAAa,QAAQ,mBAAkB;AA0CtF;;;;;;;;;CASC,GACD,OAAO,eAAeC,cAAc,EAClCC,OAAO,EACPC,aAAa,OAAO,EACpBC,MAAM,EACNC,QAAQ,EACRC,QAAQ,EAAE,EACVC,MAAM,EACNC,OAAO,EACPC,KAAK,EACLC,YAAY,EACM;IAClB,MAAMC,IAAIF,MAAMG,IAAI;IACpB,IAAI,CAACD,GAAG;QAAC,OAAO,EAAE;IAAA;IAElB,MAAME,MAAMN,UAAUP,cAAcO,QAAQH,UAAUG,SAASR,iBAAiBK;IAChF,MAAMU,MAAMC,KAAKC,GAAG,CAACD,KAAKD,GAAG,CAACC,KAAKE,KAAK,CAACX,UAAU,IAAI,IAAI;IAC3D,MAAMY,SAAShB,SAASiB,QAAQ,OAAO,OAAO;IAE9C,IAAIC,OAAkB,EAAE;IACxB,IAAI;QACF,MAAMC,MAAM,MAAMb,QAAQc,IAAI,CAAC;YAC7BnB,YAAYA;YACZoB,OAAO;YACPjB,OAAOQ,MAAM;YACbP,QAAQM;YACRW,OA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b/dist/modules/mcp/createMcpRoute.d.ts new file mode 100644 index 0000000..653e5e0 --- /dev/null +++ b/dist/modules/mcp/createMcpRoute.d.ts @@ -0,0 +1,26 @@ +import type { BasePayload } from 'payload'; +import type { ContentOption } from '../content/index.js'; +import type { I18nConfig } from '../i18n/index.js'; +type CreateMcpRouteArgs = { + /** Absolute origin for building result URLs. */ + baseUrl?: string; + /** Pages collection. Default 'pages'. */ + collection?: string; + config: I18nConfig; + /** Archive-backed collections (same as the plugin option) for get_page. */ + content?: ContentOption; + getCachedPayload: () => Promise; + /** Server name advertised in `initialize`. Default 'ipal-site'. */ + serverName?: string; + /** Server version advertised in `initialize`. Default '1.0.0'. */ + serverVersion?: string; + /** SiteSettings slug. Default 'site-settings'. */ + settingsSlug?: string; + /** Field holding a richer AI summary (buildSummaryField) to prefer in search results. */ + summaryField?: string; +}; +export declare function createMcpRoute(args: CreateMcpRouteArgs): { + GET: () => Promise; + POST: (req: Request) => Promise; +}; +export {}; diff --git a/dist/modules/mcp/createMcpRoute.js b/dist/modules/mcp/createMcpRoute.js new file mode 100644 index 0000000..7bcd0a8 --- /dev/null +++ b/dist/modules/mcp/createMcpRoute.js @@ -0,0 +1,257 @@ +import { createMarkdownRenderer, searchContent } from '../content/index.js'; +import { getDefaultLocale, isValidLocale } from '../i18n/index.js'; +/** + * A read-only MCP (Model Context Protocol) server for the client site, as a Next + * route handler. Lets Claude / any MCP client CONNECT to the site and query it + * directly — search content, fetch a page as Markdown — instead of scraping + * HTML. This is the "better integration" layer on top of the Markdown/llms work. + * + * Dependency-free on purpose: it does NOT pull in @modelcontextprotocol/sdk + * (that would be an imposed dependency, and its API moves). It implements the + * minimal JSON-RPC surface a read-only server needs over the Streamable-HTTP + * transport: initialize, tools/list, tools/call, ping. Uses the global + * Request/Response — no next/server import. + * + * Exposes two tools: + * - search_content({ query, locale?, limit? }) → matching pages (title, url, description) + * - get_page({ path }) → that page as Markdown + * + * // app/api/mcp/route.ts + * import { createMcpRoute } from '@intecion/ipal-kit' + * import { getCachedPayload } from '@/lib/content' + * import { i18nConfig } from '@/i18n.config' + * export const dynamic = 'force-dynamic' + * const mcp = createMcpRoute({ getCachedPayload, config: i18nConfig, + * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, serverName: 'acme-site' }) + * export const POST = mcp.POST + * export const GET = mcp.GET + * + * Add it in Claude as a custom connector pointing at https://site/api/mcp. + */ const DEFAULT_PROTOCOL = '2025-06-18'; +function rpcResult(id, result) { + return { + id, + jsonrpc: '2.0', + result + }; +} +function rpcError(id, code, message) { + return { + id, + error: { + code, + message + }, + jsonrpc: '2.0' + }; +} +function toolText(text, isError = false) { + return { + content: [ + { + type: 'text', + text + } + ], + ...isError ? { + isError: true + } : {} + }; +} +export function createMcpRoute(args) { + const { baseUrl, collection = 'pages', config, content, getCachedPayload, serverName = 'ipal-site', serverVersion = '1.0.0', settingsSlug = 'site-settings', summaryField } = args; + const origin = baseUrl?.replace(/\/$/, '') ?? ''; + const renderMarkdown = createMarkdownRenderer({ + collection, + content, + settingsSlug + }); + const TOOLS = [ + { + name: 'search_content', + description: 'Search the site content by keyword. Returns matching pages with title, URL and description.', + inputSchema: { + type: 'object', + properties: { + limit: { + type: 'number', + description: 'Max results (default 10)' + }, + locale: { + type: 'string', + description: `Locale code (default ${config.defaultLocale})` + }, + query: { + type: 'string', + description: 'Search keywords' + } + }, + required: [ + 'query' + ] + } + }, + { + name: 'get_page', + description: 'Fetch a single page rendered as clean Markdown. `path` is the page path, e.g. /pl/o-nas.', + inputSchema: { + type: 'object', + properties: { + path: { + type: 'string', + description: 'Page path, e.g. /pl/o-nas or /en/about' + } + }, + required: [ + 'path' + ] + } + } + ]; + async function runSearch(params) { + const query = typeof params.query === 'string' ? params.query.trim() : ''; + if (!query) { + return 'No query provided.'; + } + const locale = typeof params.locale === 'string' && isValidLocale(params.locale, config) ? params.locale : getDefaultLocale(config); + const limit = typeof params.limit === 'number' ? params.limit : 10; + const payload = await getCachedPayload(); + // Shared with the JSON search route — one ranking everywhere. + const results = await searchContent({ + baseUrl: origin, + collection, + config, + limit, + locale, + payload, + query, + summaryField + }); + if (results.length === 0) { + return `No pages matched "${query}".`; + } + return results.map((r)=>`- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`).join('\n'); + } + async function getPage(params) { + const raw = typeof params.path === 'string' ? params.path.trim() : ''; + if (!raw) { + return 'No path provided.'; + } + const segments = raw.replace(/^\/+|\/+$/g, '').split('/').filter(Boolean); + let locale = getDefaultLocale(config); + let slug = segments; + if (segments.length && isValidLocale(segments[0], config)) { + locale = segments[0]; + slug = segments.slice(1); + } + const payload = await getCachedPayload(); + const md = await renderMarkdown({ + slug, + locale, + payload + }); + return md ?? `No page found at ${raw}.`; + } + async function handleOne(msg) { + const { id = null, method, params } = msg; + // Notifications (no id) get no response body. + if (id === null && typeof method === 'string' && method.startsWith('notifications/')) { + return null; + } + switch(method){ + case 'initialize': + { + const requested = params?.protocolVersion; + return rpcResult(id, { + capabilities: { + tools: { + listChanged: false + } + }, + protocolVersion: requested || DEFAULT_PROTOCOL, + serverInfo: { + name: serverName, + version: serverVersion + } + }); + } + case 'ping': + return rpcResult(id, {}); + case 'tools/call': + { + const p = params ?? {}; + const toolArgs = p.arguments ?? {}; + try { + if (p.name === 'search_content') { + return rpcResult(id, toolText(await runSearch(toolArgs))); + } + if (p.name === 'get_page') { + return rpcResult(id, toolText(await getPage(toolArgs))); + } + return rpcResult(id, toolText(`Unknown tool: ${p.name}`, true)); + } catch (err) { + return rpcResult(id, toolText(err instanceof Error ? err.message : 'Tool error', true)); + } + } + case 'tools/list': + return rpcResult(id, { + tools: TOOLS + }); + default: + if (id === null) { + return null; + } // unknown notification + return rpcError(id, -32601, `Method not found: ${method}`); + } + } + async function POST(req) { + let body; + try { + body = await req.json(); + } catch { + return Response.json(rpcError(null, -32700, 'Parse error'), { + status: 400 + }); + } + // Batch or single. + if (Array.isArray(body)) { + const out = (await Promise.all(body.map((m)=>handleOne(m)))).filter((r)=>r !== null); + if (out.length === 0) { + return new Response(null, { + status: 202 + }); + } + return Response.json(out, { + headers: { + 'cache-control': 'no-store' + } + }); + } + const res = await handleOne(body); + if (res === null) { + return new Response(null, { + status: 202 + }); + } + return Response.json(res, { + headers: { + 'cache-control': 'no-store' + } + }); + } + // No server→client SSE stream in this read-only server. + async function GET() { + return new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', { + headers: { + allow: 'POST' + }, + status: 405 + }); + } + return { + GET, + POST + }; +} + +//# sourceMappingURL=createMcpRoute.js.map \ No newline at end of file diff --git a/dist/modules/mcp/createMcpRoute.js.map b/dist/modules/mcp/createMcpRoute.js.map new file mode 100644 index 0000000..7affb57 --- /dev/null +++ b/dist/modules/mcp/createMcpRoute.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/mcp/createMcpRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { ContentOption } from '../content/index.js'\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { createMarkdownRenderer, searchContent } from '../content/index.js'\nimport { getDefaultLocale, isValidLocale } from '../i18n/index.js'\n\n/**\n * A read-only MCP (Model Context Protocol) server for the client site, as a Next\n * route handler. Lets Claude / any MCP client CONNECT to the site and query it\n * directly — search content, fetch a page as Markdown — instead of scraping\n * HTML. This is the \"better integration\" layer on top of the Markdown/llms work.\n *\n * Dependency-free on purpose: it does NOT pull in @modelcontextprotocol/sdk\n * (that would be an imposed dependency, and its API moves). It implements the\n * minimal JSON-RPC surface a read-only server needs over the Streamable-HTTP\n * transport: initialize, tools/list, tools/call, ping. Uses the global\n * Request/Response — no next/server import.\n *\n * Exposes two tools:\n * - search_content({ query, locale?, limit? }) → matching pages (title, url, description)\n * - get_page({ path }) → that page as Markdown\n *\n * // app/api/mcp/route.ts\n * import { createMcpRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * const mcp = createMcpRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, serverName: 'acme-site' })\n * export const POST = mcp.POST\n * export const GET = mcp.GET\n *\n * Add it in Claude as a custom connector pointing at https://site/api/mcp.\n */\n\nconst DEFAULT_PROTOCOL = '2025-06-18'\n\ntype CreateMcpRouteArgs = {\n /** Absolute origin for building result URLs. */\n baseUrl?: string\n /** Pages collection. Default 'pages'. */\n collection?: string\n config: I18nConfig\n /** Archive-backed collections (same as the plugin option) for get_page. */\n content?: ContentOption\n getCachedPayload: () => Promise\n /** Server name advertised in `initialize`. Default 'ipal-site'. */\n serverName?: string\n /** Server version advertised in `initialize`. Default '1.0.0'. */\n serverVersion?: string\n /** SiteSettings slug. Default 'site-settings'. */\n settingsSlug?: string\n /** Field holding a richer AI summary (buildSummaryField) to prefer in search results. */\n summaryField?: string\n}\n\ntype JsonRpcId = null | number | string\ntype JsonRpcRequest = { id?: JsonRpcId; jsonrpc?: string; method?: string; params?: unknown }\n\nfunction rpcResult(id: JsonRpcId, result: unknown) {\n return { id, jsonrpc: '2.0', result }\n}\nfunction rpcError(id: JsonRpcId, code: number, message: string) {\n return { id, error: { code, message }, jsonrpc: '2.0' }\n}\n\nfunction toolText(text: string, isError = false) {\n return { content: [{ type: 'text', text }], ...(isError ? { isError: true } : {}) }\n}\n\nexport function createMcpRoute(args: CreateMcpRouteArgs) {\n const {\n baseUrl,\n collection = 'pages',\n config,\n content,\n getCachedPayload,\n serverName = 'ipal-site',\n serverVersion = '1.0.0',\n settingsSlug = 'site-settings',\n summaryField,\n } = args\n\n const origin = baseUrl?.replace(/\\/$/, '') ?? ''\n const renderMarkdown = createMarkdownRenderer({ collection, content, settingsSlug })\n\n const TOOLS = [\n {\n name: 'search_content',\n description:\n 'Search the site content by keyword. Returns matching pages with title, URL and description.',\n inputSchema: {\n type: 'object',\n properties: {\n limit: { type: 'number', description: 'Max results (default 10)' },\n locale: { type: 'string', description: `Locale code (default ${config.defaultLocale})` },\n query: { type: 'string', description: 'Search keywords' },\n },\n required: ['query'],\n },\n },\n {\n name: 'get_page',\n description:\n 'Fetch a single page rendered as clean Markdown. `path` is the page path, e.g. /pl/o-nas.',\n inputSchema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Page path, e.g. /pl/o-nas or /en/about' },\n },\n required: ['path'],\n },\n },\n ]\n\n async function runSearch(params: Record): Promise {\n const query = typeof params.query === 'string' ? params.query.trim() : ''\n if (!query) {return 'No query provided.'}\n const locale =\n typeof params.locale === 'string' && isValidLocale(params.locale, config)\n ? params.locale\n : getDefaultLocale(config)\n const limit = typeof params.limit === 'number' ? params.limit : 10\n\n const payload = await getCachedPayload()\n // Shared with the JSON search route — one ranking everywhere.\n const results = await searchContent({\n baseUrl: origin,\n collection,\n config,\n limit,\n locale,\n payload,\n query,\n summaryField,\n })\n if (results.length === 0) {return `No pages matched \"${query}\".`}\n return results\n .map((r) => `- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`)\n .join('\\n')\n }\n\n async function getPage(params: Record): Promise {\n const raw = typeof params.path === 'string' ? params.path.trim() : ''\n if (!raw) {return 'No path provided.'}\n const segments = raw\n .replace(/^\\/+|\\/+$/g, '')\n .split('/')\n .filter(Boolean)\n let locale = getDefaultLocale(config)\n let slug = segments\n if (segments.length && isValidLocale(segments[0], config)) {\n locale = segments[0]\n slug = segments.slice(1)\n }\n const payload = await getCachedPayload()\n const md = await renderMarkdown({ slug, locale, payload })\n return md ?? `No page found at ${raw}.`\n }\n\n async function handleOne(msg: JsonRpcRequest): Promise {\n const { id = null, method, params } = msg\n\n // Notifications (no id) get no response body.\n if (id === null && typeof method === 'string' && method.startsWith('notifications/')) {\n return null\n }\n\n switch (method) {\n case 'initialize': {\n const requested = (params as { protocolVersion?: string } | undefined)?.protocolVersion\n return rpcResult(id, {\n capabilities: { tools: { listChanged: false } },\n protocolVersion: requested || DEFAULT_PROTOCOL,\n serverInfo: { name: serverName, version: serverVersion },\n })\n }\n case 'ping':\n return rpcResult(id, {})\n case 'tools/call': {\n const p = (params ?? {}) as { arguments?: Record; name?: string }\n const toolArgs = p.arguments ?? {}\n try {\n if (p.name === 'search_content') {return rpcResult(id, toolText(await runSearch(toolArgs)))}\n if (p.name === 'get_page') {return rpcResult(id, toolText(await getPage(toolArgs)))}\n return rpcResult(id, toolText(`Unknown tool: ${p.name}`, true))\n } catch (err) {\n return rpcResult(id, toolText(err instanceof Error ? err.message : 'Tool error', true))\n }\n }\n case 'tools/list':\n return rpcResult(id, { tools: TOOLS })\n default:\n if (id === null) {return null} // unknown notification\n return rpcError(id, -32601, `Method not found: ${method}`)\n }\n }\n\n async function POST(req: Request): Promise {\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return Response.json(rpcError(null, -32700, 'Parse error'), { status: 400 })\n }\n\n // Batch or single.\n if (Array.isArray(body)) {\n const out = (await Promise.all(body.map((m) => handleOne(m as JsonRpcRequest)))).filter(\n (r): r is object => r !== null,\n )\n if (out.length === 0) {return new Response(null, { status: 202 })}\n return Response.json(out, { headers: { 'cache-control': 'no-store' } })\n }\n\n const res = await handleOne(body as JsonRpcRequest)\n if (res === null) {return new Response(null, { status: 202 })}\n return Response.json(res, { headers: { 'cache-control': 'no-store' } })\n }\n\n // No server→client SSE stream in this read-only server.\n async function GET(): Promise {\n return new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', {\n headers: { allow: 'POST' },\n status: 405,\n })\n }\n\n return { GET, POST }\n}\n"],"names":["createMarkdownRenderer","searchContent","getDefaultLocale","isValidLocale","DEFAULT_PROTOCOL","rpcResult","id","result","jsonrpc","rpcError","code","message","error","toolText","text","isError","content","type","createMcpRoute","args","baseUrl","collection","config","getCachedPayload","serverName","serverVersion","settingsSlug","summaryField","origin","replace","renderMarkdown","TOOLS","name","description","inputSchema","properties","limit","locale","defaultLocale","query","required","path","runSearch","params","trim","payload","results","length","map","r","title","url","join","getPage","raw","segments","split","filter","Boolean","slug","slice","md","handleOne","msg","method","startsWith","requested","protocolVersion","capabilities","tools","listChanged","serverInfo","version","p","toolArgs","arguments","err","Error","POST","req","body","json","Response","status","Array","isArray","out","Promise","all","m","headers","res","GET","allow"],"mappings":"AAKA,SAASA,sBAAsB,EAAEC,aAAa,QAAQ,sBAAqB;AAC3E,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,mBAAkB;AAElE;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GAED,MAAMC,mBAAmB;AAwBzB,SAASC,UAAUC,EAAa,EAAEC,MAAe;IAC/C,OAAO;QAAED;QAAIE,SAAS;QAAOD;IAAO;AACtC;AACA,SAASE,SAASH,EAAa,EAAEI,IAAY,EAAEC,OAAe;IAC5D,OAAO;QAAEL;QAAIM,OAAO;YAAEF;YAAMC;QAAQ;QAAGH,SAAS;IAAM;AACxD;AAEA,SAASK,SAASC,IAAY,EAAEC,UAAU,KAAK;IAC7C,OAAO;QAAEC,SAAS;YAAC;gBAAEC,MAAM;gBAAQH;YAAK;SAAE;QAAE,GAAIC,UAAU;YAAEA,SAAS;QAAK,IAAI,CAAC,CAAC;IAAE;AACpF;AAEA,OAAO,SAASG,eAAeC,IAAwB;IACrD,MAAM,EACJC,OAAO,EACPC,aAAa,OAAO,EACpBC,MAAM,EACNN,OAAO,EACPO,gBAAgB,EAChBC,aAAa,WAAW,EACxBC,gBAAgB,OAAO,EACvBC,eAAe,eAAe,EAC9BC,YAAY,EACb,GAAGR;IAEJ,MAAMS,SAASR,SAASS,QAAQ,OAAO,OAAO;IAC9C,MAAMC,iBAAiB9B,uBAAuB;QAAEqB;QAAYL;QAASU;IAAa;IAElF,MAAMK,QAAQ;QACZ;YACEC,MAAM;YACNC,aACE;YACFC,aAAa;gBACXjB,MAAM;gBACNkB,YAAY;oBACVC,OAAO;wBAAEnB,MAAM;wBAAUgB,aAAa;oBAA2B;oBACjEI,QAAQ;wBAAEpB,MAAM;wBAAUgB,aAAa,CAAC,qBAAqB,EAAEX,OAAOgB,aAAa,CAAC,CAAC,CAAC;oBAAC;o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BAAE,iBAAiB;YAAW;QAAE;IACvE;IAEA,wDAAwD;IACxD,eAAeE;QACb,OAAO,IAAIV,SAAS,wDAAwD;YAC1EQ,SAAS;gBAAEG,OAAO;YAAO;YACzBV,QAAQ;QACV;IACF;IAEA,OAAO;QAAES;QAAKd;IAAK;AACrB"} \ No newline at end of file diff --git a/dist/modules/mcp/index.d.ts b/dist/modules/mcp/index.d.ts new file mode 100644 index 0000000..d18eb3f --- /dev/null +++ b/dist/modules/mcp/index.d.ts @@ -0,0 +1 @@ +export { createMcpRoute } from './createMcpRoute.js'; diff --git a/dist/modules/mcp/index.js b/dist/modules/mcp/index.js new file mode 100644 index 0000000..7d313cc --- /dev/null +++ b/dist/modules/mcp/index.js @@ -0,0 +1,3 @@ +export { createMcpRoute } from './createMcpRoute.js'; + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/modules/mcp/index.js.map b/dist/modules/mcp/index.js.map new file mode 100644 index 0000000..8eca0d1 --- /dev/null +++ b/dist/modules/mcp/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/mcp/index.ts"],"sourcesContent":["export { createMcpRoute } from './createMcpRoute.js'\n"],"names":["createMcpRoute"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAqB"} \ No newline at end of file diff --git a/dist/modules/richtext/index.d.ts b/dist/modules/richtext/index.d.ts index 00ca01e..b19bf5b 100644 --- a/dist/modules/richtext/index.d.ts +++ b/dist/modules/richtext/index.d.ts @@ -1,2 +1,3 @@ +export { lexicalToMarkdown } from './lexicalToMarkdown.js'; export { RenderRichText } from './RenderRichText.js'; export type { RenderRichTextProps } from './RenderRichText.js'; diff --git a/dist/modules/richtext/index.js b/dist/modules/richtext/index.js index 9a4d947..84d8511 100644 --- a/dist/modules/richtext/index.js +++ b/dist/modules/richtext/index.js @@ -1,3 +1,4 @@ +export { lexicalToMarkdown } from './lexicalToMarkdown.js'; export { RenderRichText } from './RenderRichText.js'; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/modules/richtext/index.js.map b/dist/modules/richtext/index.js.map index 393d8d2..7335e8c 100644 --- a/dist/modules/richtext/index.js.map +++ b/dist/modules/richtext/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/richtext/index.ts"],"sourcesContent":["export { RenderRichText } from './RenderRichText.js'\nexport type { RenderRichTextProps } from './RenderRichText.js'\n"],"names":["RenderRichText"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAqB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/richtext/index.ts"],"sourcesContent":["export { lexicalToMarkdown } from './lexicalToMarkdown.js'\nexport { RenderRichText } from './RenderRichText.js'\nexport type { RenderRichTextProps } from './RenderRichText.js'\n"],"names":["lexicalToMarkdown","RenderRichText"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,cAAc,QAAQ,sBAAqB"} \ No newline at end of file diff --git a/dist/modules/richtext/lexicalToMarkdown.d.ts b/dist/modules/richtext/lexicalToMarkdown.d.ts new file mode 100644 index 0000000..bf78855 --- /dev/null +++ b/dist/modules/richtext/lexicalToMarkdown.d.ts @@ -0,0 +1,2 @@ +import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'; +export declare function lexicalToMarkdown(data: null | SerializedEditorState | undefined): string; diff --git a/dist/modules/richtext/lexicalToMarkdown.js b/dist/modules/richtext/lexicalToMarkdown.js new file mode 100644 index 0000000..1feace2 --- /dev/null +++ b/dist/modules/richtext/lexicalToMarkdown.js @@ -0,0 +1,137 @@ +// Lexical text format bitflags. +const IS_BOLD = 1; +const IS_ITALIC = 1 << 1; +const IS_STRIKETHROUGH = 1 << 2; +const IS_CODE = 1 << 4; +function isNodeArray(value) { + return Array.isArray(value); +} +function wrapText(text, format) { + if (!text) { + return text; + } + // Don't wrap pure whitespace — would produce "** **". + if (!text.trim()) { + return text; + } + let out = text; + if (format & IS_CODE) { + out = `\`${out}\``; + } + if (format & IS_BOLD) { + out = `**${out}**`; + } + if (format & IS_ITALIC) { + out = `_${out}_`; + } + if (format & IS_STRIKETHROUGH) { + out = `~~${out}~~`; + } + return out; +} +/** Render inline children (text, links, line breaks) to a single string. */ function inline(nodes) { + if (!isNodeArray(nodes)) { + return ''; + } + let out = ''; + for (const node of nodes){ + if (!node || typeof node !== 'object') { + continue; + } + const type = node.type; + if (type === 'text') { + const text = typeof node.text === 'string' ? node.text : ''; + const format = typeof node.format === 'number' ? node.format : 0; + out += wrapText(text, format); + } else if (type === 'linebreak') { + out += '\n'; + } else if (type === 'link') { + const fields = node.fields ?? {}; + const url = typeof fields.url === 'string' ? fields.url : typeof fields.doc?.value === 'string' ? fields.doc.value : ''; + const label = inline(node.children); + out += url ? `[${label}](${url})` : label; + } else if (node.children) { + out += inline(node.children); + } else if (typeof node.text === 'string') { + out += node.text; + } + } + return out; +} +/** Render a list (ordered/unordered), handling nesting via indentation. */ function renderList(node, depth) { + const ordered = node.listType === 'number'; + const items = isNodeArray(node.children) ? node.children : []; + const indent = ' '.repeat(depth); + const lines = []; + let i = 1; + for (const item of items){ + if (!item || typeof item !== 'object') { + continue; + } + const marker = ordered ? `${i}.` : '-'; + // A listitem may contain inline content and/or a nested list. + const kids = isNodeArray(item.children) ? item.children : []; + const nested = kids.filter((k)=>k && typeof k === 'object' && k.type === 'list'); + const inlineKids = kids.filter((k)=>!(k && typeof k === 'object' && k.type === 'list')); + const text = inline(inlineKids); + if (text.trim()) { + lines.push(`${indent}${marker} ${text}`); + i++; + } + for (const n of nested){ + lines.push(renderList(n, depth + 1)); + } + } + return lines.join('\n'); +} +/** Render a block-level node to Markdown. */ function block(node) { + const type = node.type; + switch(type){ + case 'heading': + { + const level = typeof node.tag === 'string' ? Number(node.tag.replace('h', '')) || 2 : 2; + return `${'#'.repeat(Math.min(level, 6))} ${inline(node.children)}`; + } + case 'horizontalrule': + return '---'; + case 'list': + return renderList(node, 0); + case 'paragraph': + { + const text = inline(node.children); + return text.trim() ? text : ''; + } + case 'quote': + return inline(node.children).split('\n').map((l)=>`> ${l}`).join('\n'); + case 'upload': + { + const value = node.value ?? {}; + const url = typeof value.url === 'string' ? value.url : ''; + const alt = typeof value.alt === 'string' ? value.alt : ''; + return url ? `![${alt}](${url})` : ''; + } + default: + // Unknown block-level node: emit its inline content if any. + return node.children ? inline(node.children) : ''; + } +} +export function lexicalToMarkdown(data) { + const root = data?.root; + if (!root || !isNodeArray(root.children)) { + return ''; + } + const blocks = []; + for (const node of root.children){ + if (!node || typeof node !== 'object') { + continue; + } + const md = block(node); + if (md.trim()) { + blocks.push(md); + } + } + // Blank line between block-level elements — standard Markdown separation. + return blocks.join('\n\n').trim(); +} + +//# sourceMappingURL=lexicalToMarkdown.js.map \ No newline at end of file diff --git a/dist/modules/richtext/lexicalToMarkdown.js.map b/dist/modules/richtext/lexicalToMarkdown.js.map new file mode 100644 index 0000000..9911e23 --- /dev/null +++ b/dist/modules/richtext/lexicalToMarkdown.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/richtext/lexicalToMarkdown.ts"],"sourcesContent":["import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'\n\n/**\n * Converts a Payload Lexical richText value to Markdown — a small, dependency-\n * free walker over the serialized node tree. Self-contained on purpose: it does\n * NOT rely on a specific `@payloadcms/richtext-lexical` markdown export (those\n * move between versions), so a Payload bump can't break it. Covers the node\n * types editors actually produce; unknown nodes degrade to their text/children\n * rather than throwing.\n *\n * Used for AI-readable output (per-page Markdown, llms-full.txt) — give an agent\n * clean Markdown instead of making it parse HTML. For on-page rendering use\n * RenderRichText (the official React converter); this is the text-only sibling.\n */\n\ntype LexNode = { children?: unknown; type?: string } & Record\n\n// Lexical text format bitflags.\nconst IS_BOLD = 1\nconst IS_ITALIC = 1 << 1\nconst IS_STRIKETHROUGH = 1 << 2\nconst IS_CODE = 1 << 4\n\nfunction isNodeArray(value: unknown): value is LexNode[] {\n return Array.isArray(value)\n}\n\nfunction wrapText(text: string, format: number): string {\n if (!text) {return text}\n // Don't wrap pure whitespace — would produce \"** **\".\n if (!text.trim()) {return text}\n let out = text\n if (format & IS_CODE) {out = `\\`${out}\\``}\n if (format & IS_BOLD) {out = `**${out}**`}\n if (format & IS_ITALIC) {out = `_${out}_`}\n if (format & IS_STRIKETHROUGH) {out = `~~${out}~~`}\n return out\n}\n\n/** Render inline children (text, links, line breaks) to a single string. */\nfunction inline(nodes: unknown): string {\n if (!isNodeArray(nodes)) {return ''}\n let out = ''\n for (const node of nodes) {\n if (!node || typeof node !== 'object') {continue}\n const type = node.type\n\n if (type === 'text') {\n const text = typeof node.text === 'string' ? node.text : ''\n const format = typeof node.format === 'number' ? node.format : 0\n out += wrapText(text, format)\n } else if (type === 'linebreak') {\n out += '\\n'\n } else if (type === 'link') {\n const fields = (node.fields ?? {}) as Record\n const url =\n typeof fields.url === 'string'\n ? fields.url\n : typeof (fields.doc as Record)?.value === 'string'\n ? ((fields.doc as Record).value as string)\n : ''\n const label = inline(node.children)\n out += url ? `[${label}](${url})` : label\n } else if (node.children) {\n out += inline(node.children)\n } else if (typeof node.text === 'string') {\n out += node.text\n }\n }\n return out\n}\n\n/** Render a list (ordered/unordered), handling nesting via indentation. */\nfunction renderList(node: LexNode, depth: number): string {\n const ordered = node.listType === 'number'\n const items = isNodeArray(node.children) ? node.children : []\n const indent = ' '.repeat(depth)\n const lines: string[] = []\n let i = 1\n for (const item of items) {\n if (!item || typeof item !== 'object') {continue}\n const marker = ordered ? `${i}.` : '-'\n // A listitem may contain inline content and/or a nested list.\n const kids = isNodeArray(item.children) ? item.children : []\n const nested = kids.filter((k) => k && typeof k === 'object' && k.type === 'list')\n const inlineKids = kids.filter((k) => !(k && typeof k === 'object' && k.type === 'list'))\n const text = inline(inlineKids)\n if (text.trim()) {\n lines.push(`${indent}${marker} ${text}`)\n i++\n }\n for (const n of nested) {lines.push(renderList(n, depth + 1))}\n }\n return lines.join('\\n')\n}\n\n/** Render a block-level node to Markdown. */\nfunction block(node: LexNode): string {\n const type = node.type\n\n switch (type) {\n case 'heading': {\n const level = typeof node.tag === 'string' ? Number(node.tag.replace('h', '')) || 2 : 2\n return `${'#'.repeat(Math.min(level, 6))} ${inline(node.children)}`\n }\n case 'horizontalrule':\n return '---'\n case 'list':\n return renderList(node, 0)\n case 'paragraph': {\n const text = inline(node.children)\n return text.trim() ? text : ''\n }\n case 'quote':\n return inline(node.children)\n .split('\\n')\n .map((l) => `> ${l}`)\n .join('\\n')\n case 'upload': {\n const value = (node.value ?? {}) as Record\n const url = typeof value.url === 'string' ? value.url : ''\n const alt = typeof value.alt === 'string' ? value.alt : ''\n return url ? `![${alt}](${url})` : ''\n }\n default:\n // Unknown block-level node: emit its inline content if any.\n return node.children ? inline(node.children) : ''\n }\n}\n\nexport function lexicalToMarkdown(data: null | SerializedEditorState | undefined): string {\n const root = (data as unknown as { root?: LexNode } | null | undefined)?.root\n if (!root || !isNodeArray(root.children)) {return ''}\n\n const blocks: string[] = []\n for (const node of root.children) {\n if (!node || typeof node !== 'object') {continue}\n const md = block(node)\n if (md.trim()) {blocks.push(md)}\n }\n // Blank line between block-level elements — standard Markdown separation.\n return blocks.join('\\n\\n').trim()\n}\n"],"names":["IS_BOLD","IS_ITALIC","IS_STRIKETHROUGH","IS_CODE","isNodeArray","value","Array","isArray","wrapText","text","format","trim","out","inline","nodes","node","type","fields","url","doc","label","children","renderList","depth","ordered","listType","items","indent","repeat","lines","i","item","marker","kids","nested","filter","k","inlineKids","push","n","join","block","level","tag","Number","replace","Math","min","split","map","l","alt","lexicalToMarkdown","data","root","blocks","md"],"mappings":"AAiBA,gCAAgC;AAChC,MAAMA,UAAU;AAChB,MAAMC,YAAY,KAAK;AACvB,MAAMC,mBAAmB,KAAK;AAC9B,MAAMC,UAAU,KAAK;AAErB,SAASC,YAAYC,KAAc;IACjC,OAAOC,MAAMC,OAAO,CAACF;AACvB;AAEA,SAASG,SAASC,IAAY,EAAEC,MAAc;IAC5C,IAAI,CAACD,MAAM;QAAC,OAAOA;IAAI;IACvB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K,MAAMxC,QAAQuC,KAAKjC,QAAQ,CAAE;QAChC,IAAI,CAACN,QAAQ,OAAOA,SAAS,UAAU;YAAC;QAAQ;QAChD,MAAMyC,KAAKf,MAAM1B;QACjB,IAAIyC,GAAG7C,IAAI,IAAI;YAAC4C,OAAOjB,IAAI,CAACkB;QAAG;IACjC;IACA,0EAA0E;IAC1E,OAAOD,OAAOf,IAAI,CAAC,QAAQ7B,IAAI;AACjC"} \ No newline at end of file diff --git a/dist/modules/seo/buildLlmsTxt.d.ts b/dist/modules/seo/buildLlmsTxt.d.ts index 1d019b3..378e593 100644 --- a/dist/modules/seo/buildLlmsTxt.d.ts +++ b/dist/modules/seo/buildLlmsTxt.d.ts @@ -4,6 +4,15 @@ type BuildLlmsTxtArgs = { /** Absolute site URL (https://…). */ baseUrl: string; config: I18nConfig; + /** + * Full-content mode (llms-full.txt). When true, each page's full body is + * inlined as Markdown (via blocksToMarkdown) under its heading, so an agent + * gets the whole site in one request — the llmstxt.org "llms-full.txt" + * convention. Default false = the compact index (links + descriptions). + */ + full?: boolean; + /** Field holding the block layout (full mode only). Default 'layout'. */ + layoutField?: string; /** Locale for names/descriptions. Defaults to config.defaultLocale. */ locale?: string; /** Pages collection slug. Defaults to 'pages'. */ @@ -11,6 +20,11 @@ type BuildLlmsTxtArgs = { payload: BasePayload; /** Site settings global slug. Defaults to 'site-settings'. */ settingsSlug?: string; + /** + * Field holding a richer AI summary (buildSummaryField). When set and present, + * it's used as the page description instead of meta.description. + */ + summaryField?: string; }; /** * Builds the body of /llms.txt — a Markdown file describing the site for AI @@ -41,5 +55,5 @@ type BuildLlmsTxtArgs = { * Data comes from the panel (siteName, siteDescription, pages) — nothing * hardcoded. Skips drafts and noindex pages (same as the sitemap). */ -export declare function buildLlmsTxt({ baseUrl, config, locale, pagesSlug, payload, settingsSlug, }: BuildLlmsTxtArgs): Promise; +export declare function buildLlmsTxt({ baseUrl, config, full, layoutField, locale, pagesSlug, payload, settingsSlug, summaryField, }: BuildLlmsTxtArgs): Promise; export {}; diff --git a/dist/modules/seo/buildLlmsTxt.js b/dist/modules/seo/buildLlmsTxt.js index cfc27f1..911c41f 100644 --- a/dist/modules/seo/buildLlmsTxt.js +++ b/dist/modules/seo/buildLlmsTxt.js @@ -1,3 +1,4 @@ +import { blocksToMarkdown } from '../content/blocksToMarkdown.js'; import { buildLocalizedPath } from '../i18n/index.js'; /** * Builds the body of /llms.txt — a Markdown file describing the site for AI @@ -27,7 +28,13 @@ import { buildLocalizedPath } from '../i18n/index.js'; * * Data comes from the panel (siteName, siteDescription, pages) — nothing * hardcoded. Skips drafts and noindex pages (same as the sitemap). - */ export async function buildLlmsTxt({ baseUrl, config, locale, pagesSlug = 'pages', payload, settingsSlug = 'site-settings' }) { + */ export async function buildLlmsTxt({ baseUrl, config, full = false, layoutField = 'layout', locale, pagesSlug = 'pages', payload, settingsSlug = 'site-settings', summaryField }) { + const pickDescription = (raw)=>{ + if (summaryField && typeof raw[summaryField] === 'string' && raw[summaryField].trim()) { + return raw[summaryField].trim(); + } + return typeof raw.meta?.description === 'string' ? raw.meta.description : undefined; + }; const loc = locale ?? config.defaultLocale; const origin = baseUrl.replace(/\/$/, ''); const settings = await payload.findGlobal({ @@ -42,9 +49,10 @@ import { buildLocalizedPath } from '../i18n/index.js'; // "path cannot be queried: _status" (a real bug report). Draft filtering // happens in memory below, which is safe for every collection. Same as // buildSitemapEntries and generateStaticParams. + // Full mode needs depth:1 so block images/relations populate for the Markdown. const result = await payload.find({ collection: pagesSlug, - depth: 0, + depth: full ? 1 : 0, limit: 1000, locale: loc }); @@ -55,6 +63,49 @@ import { buildLocalizedPath } from '../i18n/index.js'; if (description) { lines.push(`> ${description}`, ''); } + if (full) { + // Full-content: each published page inlined as Markdown under its heading. + const sections = []; + for (const raw of result.docs){ + if (raw._status && raw._status !== 'published') { + continue; + } + if (raw.meta?.noindex) { + continue; + } + const title = typeof raw.title === 'string' ? raw.title : undefined; + const slug = typeof raw.slug === 'string' ? raw.slug : undefined; + if (!title || !slug) { + continue; + } + const path = buildLocalizedPath({ + config, + locale: loc, + slugs: { + [loc]: slug + } + }); + const body = blocksToMarkdown(raw[layoutField]); + const desc = pickDescription(raw); + const parts = [ + `## ${title}` + ]; + if (path) { + parts.push(`${origin}${path}`); + } + if (desc) { + parts.push(`_${desc}_`); + } + if (body) { + parts.push(body); + } + sections.push(parts.join('\n\n')); + } + if (sections.length > 0) { + lines.push(sections.join('\n\n---\n\n'), ''); + } + return lines.join('\n'); + } const pageLinks = []; for (const raw of result.docs){ if (raw._status && raw._status !== 'published') { @@ -78,7 +129,8 @@ import { buildLocalizedPath } from '../i18n/index.js'; if (!path) { continue; } - const pageDesc = typeof raw.meta?.description === 'string' ? ` — ${raw.meta.description}` : ''; + const desc = pickDescription(raw); + const pageDesc = desc ? ` — ${desc}` : ''; pageLinks.push(`- [${title}](${origin}${path})${pageDesc}`); } if (pageLinks.length > 0) { diff --git a/dist/modules/seo/buildLlmsTxt.js.map b/dist/modules/seo/buildLlmsTxt.js.map index b9fedc4..fa52cc1 100644 --- a/dist/modules/seo/buildLlmsTxt.js.map +++ b/dist/modules/seo/buildLlmsTxt.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/seo/buildLlmsTxt.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { buildLocalizedPath } from '../i18n/index.js'\n\ntype BuildLlmsTxtArgs = {\n /** Absolute site URL (https://…). */\n baseUrl: string\n config: I18nConfig\n /** Locale for names/descriptions. Defaults to config.defaultLocale. */\n locale?: string\n /** Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n payload: BasePayload\n /** Site settings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n}\n\ntype SettingsShape = {\n siteDescription?: null | string\n siteName?: null | string\n}\n\ntype PageRow = {\n _status?: string\n id: number | string\n meta?: { description?: unknown; noindex?: boolean } | null\n slug?: unknown\n title?: unknown\n}\n\n/**\n * Builds the body of /llms.txt — a Markdown file describing the site for AI\n * agents / LLM crawlers, per the llmstxt.org convention. Mirrors buildRobots /\n * buildSitemapEntries: the plugin already knows the site's name, description,\n * and pages, so it can generate this automatically.\n *\n * Structure (llmstxt.org): H1 site name, a blockquote/summary, then a list of\n * key pages as Markdown links with short descriptions. Agents read this to\n * understand the site quickly without crawling everything.\n *\n * Wire it as a route that returns text/plain:\n *\n * // app/llms.txt/route.ts\n * import { buildLlmsTxt } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export async function GET() {\n * const body = await buildLlmsTxt({\n * payload: await getCachedPayload(),\n * config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!,\n * })\n * return new Response(body, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } })\n * }\n *\n * Data comes from the panel (siteName, siteDescription, pages) — nothing\n * hardcoded. Skips drafts and noindex pages (same as the sitemap).\n */\nexport async function buildLlmsTxt({\n baseUrl,\n config,\n locale,\n pagesSlug = 'pages',\n payload,\n settingsSlug = 'site-settings',\n}: BuildLlmsTxtArgs): Promise {\n const loc = locale ?? config.defaultLocale\n const origin = baseUrl.replace(/\\/$/, '')\n\n const settings = (await payload.findGlobal({\n slug: settingsSlug as never,\n depth: 0,\n locale: loc as never,\n })) as SettingsShape\n\n const name = settings.siteName?.trim() || 'Website'\n const description = settings.siteDescription?.trim()\n\n // NO where:{_status} filter — collections without drafts enabled don't\n // register the _status field, and querying it throws\n // \"path cannot be queried: _status\" (a real bug report). Draft filtering\n // happens in memory below, which is safe for every collection. Same as\n // buildSitemapEntries and generateStaticParams.\n const result = await payload.find({\n collection: pagesSlug as never,\n depth: 0,\n limit: 1000,\n locale: loc as never,\n })\n\n const lines: string[] = [`# ${name}`, '']\n if (description) {\n lines.push(`> ${description}`, '')\n }\n\n const pageLinks: string[] = []\n for (const raw of result.docs as PageRow[]) {\n if (raw._status && raw._status !== 'published') {continue}\n if (raw.meta?.noindex) {continue}\n\n const title = typeof raw.title === 'string' ? raw.title : undefined\n const slug = typeof raw.slug === 'string' ? raw.slug : undefined\n if (!title || !slug) {continue}\n\n const path = buildLocalizedPath({ config, locale: loc, slugs: { [loc]: slug } })\n if (!path) {continue}\n\n const pageDesc = typeof raw.meta?.description === 'string' ? ` — ${raw.meta.description}` : ''\n pageLinks.push(`- [${title}](${origin}${path})${pageDesc}`)\n }\n\n if (pageLinks.length > 0) {\n lines.push('## Strony', '', ...pageLinks, '')\n }\n\n return lines.join('\\n')\n}\n"],"names":["buildLocalizedPath","buildLlmsTxt","baseUrl","config","locale","pagesSlug","payload","settingsSlug","loc","defaultLocale","origin","replace","settings","findGlobal","slug","depth","name","siteName","trim","description","siteDescription","result","find","collection","limit","lines","push","pageLinks","raw","docs","_status","meta","noindex","title","undefined","path","slugs","pageDesc","length","join"],"mappings":"AAIA,SAASA,kBAAkB,QAAQ,mBAAkB;AA4BrD;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GACD,OAAO,eAAeC,aAAa,EACjCC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,YAAY,OAAO,EACnBC,OAAO,EACPC,eAAe,eAAe,EACb;IACjB,MAAMC,MAAMJ,UAAUD,OAAOM,aAAa;IAC1C,MAAMC,SAASR,QAAQS,OAAO,CAAC,OAAO;IAEtC,MAAMC,WAAY,MAAMN,QAAQO,UAAU,CAAC;QACzCC,MAAMP;QACNQ,OAAO;QACPX,QAAQI;IACV;IAEA,MAAMQ,OAAOJ,SAASK,QAAQ,EAAEC,UAAU;IAC1C,MAAMC,cAAcP,SAASQ,eAAe,EAAEF;IAE9C,uEAAuE;IACvE,qDAAqD;IACrD,yEAAyE;IACzE,uEAAuE;IACvE,gDAAgD;IAChD,MAAMG,SAAS,MAAMf,QAAQgB,IAAI,CAAC;QAChCC,YAAYlB;QACZU,OAAO;QACPS,OAAO;QACPpB,QAAQI;IACV;IAEA,MAAMiB,QAAkB;QAAC,CAAC,EAAE,EAAET,MAAM;QAAE;KAAG;IACzC,IAAIG,aAAa;QACfM,MAAMC,IAAI,CAAC,CAAC,EAAE,EAAEP,aAAa,EAAE;IACjC;IAEA,MAAMQ,YAAsB,EAAE;IAC9B,KAAK,MAAMC,OAAOP,OAAOQ,IAAI,CAAe;QAC1C,IAAID,IAAIE,OAAO,IAAIF,IAAIE,OAAO,KAAK,aAAa;YAAC;QAAQ;QACzD,IAAIF,IAAIG,IAAI,EAAEC,SAAS;YAAC;QAAQ;QAEhC,MAAMC,QAAQ,OAAOL,IAAIK,KAAK,KAAK,WAAWL,IAAIK,KAAK,GAAGC;QAC1D,MAAMpB,OAAO,OAAOc,IAAId,IAAI,KAAK,WAAWc,IAAId,IAAI,GAAGoB;QACvD,IAAI,CAACD,SAAS,CAACnB,MAAM;YAAC;QAAQ;QAE9B,MAAMqB,OAAOnC,mBAAmB;YAAEG;YAAQC,QAAQI;YAAK4B,OAAO;gBAAE,CAAC5B,IAAI,EAAEM;YAAK;QAAE;QAC9E,IAAI,CAACqB,MAAM;YAAC;QAAQ;QAEpB,MAAME,WAAW,OAAOT,IAAIG,IAAI,EAAEZ,gBAAgB,WAAW,CAAC,GAAG,EAAES,IAAIG,IAAI,CAACZ,WAAW,EAAE,GAAG;QAC5FQ,UAAUD,IAAI,CAAC,CAAC,GAAG,EAAEO,MAAM,EAAE,EAAEvB,SAASyB,KAAK,CAAC,EAAEE,UAAU;IAC5D;IAEA,IAAIV,UAAUW,MAAM,GAAG,GAAG;QACxBb,MAAMC,IAAI,CAAC,aAAa,OAAOC,WAAW;IAC5C;IAEA,OAAOF,MAAMc,IAAI,CAAC;AACpB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/seo/buildLlmsTxt.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { blocksToMarkdown } from '../content/blocksToMarkdown.js'\nimport { buildLocalizedPath } from '../i18n/index.js'\n\ntype BuildLlmsTxtArgs = {\n /** Absolute site URL (https://…). */\n baseUrl: string\n config: I18nConfig\n /**\n * Full-content mode (llms-full.txt). When true, each page's full body is\n * inlined as Markdown (via blocksToMarkdown) under its heading, so an agent\n * gets the whole site in one request — the llmstxt.org \"llms-full.txt\"\n * convention. Default false = the compact index (links + descriptions).\n */\n full?: boolean\n /** Field holding the block layout (full mode only). Default 'layout'. */\n layoutField?: string\n /** Locale for names/descriptions. Defaults to config.defaultLocale. */\n locale?: string\n /** Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n payload: BasePayload\n /** Site settings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n /**\n * Field holding a richer AI summary (buildSummaryField). When set and present,\n * it's used as the page description instead of meta.description.\n */\n summaryField?: string\n}\n\ntype SettingsShape = {\n siteDescription?: null | string\n siteName?: null | string\n}\n\ntype PageRow = {\n [key: string]: unknown\n _status?: string\n id: number | string\n meta?: { description?: unknown; noindex?: boolean } | null\n slug?: unknown\n title?: unknown\n}\n\n/**\n * Builds the body of /llms.txt — a Markdown file describing the site for AI\n * agents / LLM crawlers, per the llmstxt.org convention. Mirrors buildRobots /\n * buildSitemapEntries: the plugin already knows the site's name, description,\n * and pages, so it can generate this automatically.\n *\n * Structure (llmstxt.org): H1 site name, a blockquote/summary, then a list of\n * key pages as Markdown links with short descriptions. Agents read this to\n * understand the site quickly without crawling everything.\n *\n * Wire it as a route that returns text/plain:\n *\n * // app/llms.txt/route.ts\n * import { buildLlmsTxt } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export async function GET() {\n * const body = await buildLlmsTxt({\n * payload: await getCachedPayload(),\n * config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!,\n * })\n * return new Response(body, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } })\n * }\n *\n * Data comes from the panel (siteName, siteDescription, pages) — nothing\n * hardcoded. Skips drafts and noindex pages (same as the sitemap).\n */\nexport async function buildLlmsTxt({\n baseUrl,\n config,\n full = false,\n layoutField = 'layout',\n locale,\n pagesSlug = 'pages',\n payload,\n settingsSlug = 'site-settings',\n summaryField,\n}: BuildLlmsTxtArgs): Promise {\n const pickDescription = (raw: PageRow): string | undefined => {\n if (\n summaryField &&\n typeof raw[summaryField] === 'string' &&\n (raw[summaryField]).trim()\n ) {\n return (raw[summaryField]).trim()\n }\n return typeof raw.meta?.description === 'string' ? raw.meta.description : undefined\n }\n const loc = locale ?? config.defaultLocale\n const origin = baseUrl.replace(/\\/$/, '')\n\n const settings = (await payload.findGlobal({\n slug: settingsSlug as never,\n depth: 0,\n locale: loc as never,\n })) as SettingsShape\n\n const name = settings.siteName?.trim() || 'Website'\n const description = settings.siteDescription?.trim()\n\n // NO where:{_status} filter — collections without drafts enabled don't\n // register the _status field, and querying it throws\n // \"path cannot be queried: _status\" (a real bug report). Draft filtering\n // happens in memory below, which is safe for every collection. Same as\n // buildSitemapEntries and generateStaticParams.\n // Full mode needs depth:1 so block images/relations populate for the Markdown.\n const result = await payload.find({\n collection: pagesSlug as never,\n depth: full ? 1 : 0,\n limit: 1000,\n locale: loc as never,\n })\n\n const lines: string[] = [`# ${name}`, '']\n if (description) {\n lines.push(`> ${description}`, '')\n }\n\n if (full) {\n // Full-content: each published page inlined as Markdown under its heading.\n const sections: string[] = []\n for (const raw of result.docs as PageRow[]) {\n if (raw._status && raw._status !== 'published') {continue}\n if (raw.meta?.noindex) {continue}\n\n const title = typeof raw.title === 'string' ? raw.title : undefined\n const slug = typeof raw.slug === 'string' ? raw.slug : undefined\n if (!title || !slug) {continue}\n\n const path = buildLocalizedPath({ config, locale: loc, slugs: { [loc]: slug } })\n const body = blocksToMarkdown(raw[layoutField])\n const desc = pickDescription(raw)\n const parts = [`## ${title}`]\n if (path) {parts.push(`${origin}${path}`)}\n if (desc) {parts.push(`_${desc}_`)}\n if (body) {parts.push(body)}\n sections.push(parts.join('\\n\\n'))\n }\n if (sections.length > 0) {lines.push(sections.join('\\n\\n---\\n\\n'), '')}\n return lines.join('\\n')\n }\n\n const pageLinks: string[] = []\n for (const raw of result.docs as PageRow[]) {\n if (raw._status && raw._status !== 'published') {continue}\n if (raw.meta?.noindex) {continue}\n\n const title = typeof raw.title === 'string' ? raw.title : undefined\n const slug = typeof raw.slug === 'string' ? raw.slug : undefined\n if (!title || !slug) {continue}\n\n const path = buildLocalizedPath({ config, locale: loc, slugs: { [loc]: slug } })\n if (!path) {continue}\n\n const desc = pickDescription(raw)\n const pageDesc = desc ? ` — ${desc}` : ''\n pageLinks.push(`- [${title}](${origin}${path})${pageDesc}`)\n }\n\n if (pageLinks.length > 0) {\n lines.push('## Strony', '', ...pageLinks, '')\n }\n\n return lines.join('\\n')\n}\n"],"names":["blocksToMarkdown","buildLocalizedPath","buildLlmsTxt","baseUrl","config","full","layoutField","locale","pagesSlug","payload","settingsSlug","summaryField","pickDescription","raw","trim","meta","description","undefined","loc","defaultLocale","origin","replace","settings","findGlobal","slug","depth","name","siteName","siteDescription","result","find","collection","limit","lines","push","sections","docs","_status","noindex","title","path","slugs","body","desc","parts","join","length","pageLinks","pageDesc"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,iCAAgC;AACjE,SAASC,kBAAkB,QAAQ,mBAAkB;AA2CrD;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GACD,OAAO,eAAeC,aAAa,EACjCC,OAAO,EACPC,MAAM,EACNC,OAAO,KAAK,EACZC,cAAc,QAAQ,EACtBC,MAAM,EACNC,YAAY,OAAO,EACnBC,OAAO,EACPC,eAAe,eAAe,EAC9BC,YAAY,EACK;IACjB,MAAMC,kBAAkB,CAACC;QACvB,IACEF,gBACA,OAAOE,GAAG,CAACF,aAAa,KAAK,YAC7B,AAACE,GAAG,CAACF,aAAa,CAAEG,IAAI,IACxB;YACA,OAAO,AAACD,GAAG,CAACF,aAAa,CAAEG,IAAI;QACjC;QACA,OAAO,OAAOD,IA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AM,GAAG;QACvCI,UAAUb,IAAI,CAAC,CAAC,GAAG,EAAEK,MAAM,EAAE,EAAEnB,SAASoB,KAAK,CAAC,EAAEQ,UAAU;IAC5D;IAEA,IAAID,UAAUD,MAAM,GAAG,GAAG;QACxBb,MAAMC,IAAI,CAAC,aAAa,OAAOa,WAAW;IAC5C;IAEA,OAAOd,MAAMY,IAAI,CAAC;AACpB"} \ No newline at end of file diff --git a/dist/modules/seo/buildRobots.d.ts b/dist/modules/seo/buildRobots.d.ts index 6369a0a..f49f90b 100644 --- a/dist/modules/seo/buildRobots.d.ts +++ b/dist/modules/seo/buildRobots.d.ts @@ -1,4 +1,36 @@ +type RobotRule = { + allow?: string; + disallow?: string[]; + userAgent: string | string[]; +}; +/** + * Known AI user agents, split by purpose: + * - assistant/search bots fetch a page to answer a user's question live or to + * power an AI search index — the ones that make "the chat reads your site" + * work, and that most businesses WANT. + * - training crawlers collect pages to train models — some clients prefer to + * opt out of these while keeping assistant/search visibility. + */ +export declare const AI_ASSISTANT_BOTS: readonly ["ClaudeBot", "Claude-Web", "Claude-SearchBot", "ChatGPT-User", "OAI-SearchBot", "PerplexityBot", "Perplexity-User"]; +export declare const AI_TRAINING_BOTS: readonly ["GPTBot", "Google-Extended", "CCBot", "anthropic-ai", "Applebot-Extended", "Bytespider", "Meta-ExternalAgent"]; +type AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false; type BuildRobotsArgs = { + /** Override the assistant/search bot list. */ + aiAssistantAgents?: readonly string[]; + /** + * How to treat AI crawlers (assistant/search + training). Default 'allow' — + * explicitly welcome them so the site stays visible to Claude, ChatGPT, + * Perplexity etc. and an accidental future '*' tightening doesn't lock them + * out. Options: + * - 'allow' (default): explicit allow for assistant AND training bots. + * - 'block-training': allow assistant/search bots, disallow training crawlers + * — keep AI answers/visibility, opt out of model training. + * - 'disallow': block all known AI bots. + * - false: emit no AI-specific rules (only the '*' rule). + */ + aiBots?: AiBotsPolicy; + /** Override the training crawler list. */ + aiTrainingAgents?: readonly string[]; /** Absolute origin, e.g. 'https://example.com'. */ baseUrl: string; /** Paths to disallow. Defaults to Payload's admin and API. */ @@ -7,20 +39,18 @@ type BuildRobotsArgs = { sitemap?: boolean; }; /** - * Shape for Next's `app/robots.ts`. + * Shape for Next's `app/robots.ts`. `rules` may be a single rule or an array + * (Next accepts both) — it becomes an array when AI-bot rules are added. */ export type RobotsRules = { host?: string; - rules: { - allow?: string; - disallow?: string[]; - userAgent: string; - }; + rules: RobotRule | RobotRule[]; sitemap?: string; }; /** * Builds robots rules that allow crawling everything except the admin panel and - * API, and point crawlers at the sitemap. + * API, point crawlers at the sitemap, and (by default) explicitly welcome AI + * assistant/search/training bots. * * ```ts * // app/robots.ts @@ -31,6 +61,17 @@ export type RobotsRules = { * * The admin and API are disallowed by default — no reason for them in the index, * and it keeps crawl budget on real content. + * + * AI visibility: the #1 reason "the chat won't read the site" is an AI user + * agent being blocked (or not explicitly allowed under a tightened '*' rule). + * `aiBots: 'allow'` (default) emits explicit allow rules for ClaudeBot, GPTBot, + * PerplexityBot, Google-Extended and friends. To keep AI answers but opt out of + * model training, use `aiBots: 'block-training'`. To block them all, 'disallow'. + * + * Pass custom disallow to block parametrized/thin URLs that waste crawl budget: + * ```ts + * buildRobots({ baseUrl, disallow: ['/admin', '/api', '/*?meter=*', '/*?s=*'] }) + * ``` */ -export declare function buildRobots({ baseUrl, disallow, sitemap, }: BuildRobotsArgs): RobotsRules; +export declare function buildRobots({ aiAssistantAgents, aiBots, aiTrainingAgents, baseUrl, disallow, sitemap, }: BuildRobotsArgs): RobotsRules; export {}; diff --git a/dist/modules/seo/buildRobots.js b/dist/modules/seo/buildRobots.js index 226441f..08dc75f 100644 --- a/dist/modules/seo/buildRobots.js +++ b/dist/modules/seo/buildRobots.js @@ -1,6 +1,32 @@ +/** + * Known AI user agents, split by purpose: + * - assistant/search bots fetch a page to answer a user's question live or to + * power an AI search index — the ones that make "the chat reads your site" + * work, and that most businesses WANT. + * - training crawlers collect pages to train models — some clients prefer to + * opt out of these while keeping assistant/search visibility. + */ export const AI_ASSISTANT_BOTS = [ + 'ClaudeBot', + 'Claude-Web', + 'Claude-SearchBot', + 'ChatGPT-User', + 'OAI-SearchBot', + 'PerplexityBot', + 'Perplexity-User' +]; +export const AI_TRAINING_BOTS = [ + 'GPTBot', + 'Google-Extended', + 'CCBot', + 'anthropic-ai', + 'Applebot-Extended', + 'Bytespider', + 'Meta-ExternalAgent' +]; /** * Builds robots rules that allow crawling everything except the admin panel and - * API, and point crawlers at the sitemap. + * API, point crawlers at the sitemap, and (by default) explicitly welcome AI + * assistant/search/training bots. * * ```ts * // app/robots.ts @@ -11,17 +37,69 @@ * * The admin and API are disallowed by default — no reason for them in the index, * and it keeps crawl budget on real content. - */ export function buildRobots({ baseUrl, disallow = [ + * + * AI visibility: the #1 reason "the chat won't read the site" is an AI user + * agent being blocked (or not explicitly allowed under a tightened '*' rule). + * `aiBots: 'allow'` (default) emits explicit allow rules for ClaudeBot, GPTBot, + * PerplexityBot, Google-Extended and friends. To keep AI answers but opt out of + * model training, use `aiBots: 'block-training'`. To block them all, 'disallow'. + * + * Pass custom disallow to block parametrized/thin URLs that waste crawl budget: + * ```ts + * buildRobots({ baseUrl, disallow: ['/admin', '/api', '/*?meter=*', '/*?s=*'] }) + * ``` + */ export function buildRobots({ aiAssistantAgents = AI_ASSISTANT_BOTS, aiBots = 'allow', aiTrainingAgents = AI_TRAINING_BOTS, baseUrl, disallow = [ '/admin', '/api' ], sitemap = true }) { const origin = baseUrl.replace(/\/$/, ''); - return { - rules: { + const baseRule = { + allow: '/', + disallow, + userAgent: '*' + }; + const aiRules = []; + if (aiBots === 'allow') { + aiRules.push({ allow: '/', disallow, - userAgent: '*' - }, + userAgent: [ + ...aiAssistantAgents, + ...aiTrainingAgents + ] + }); + } else if (aiBots === 'block-training') { + aiRules.push({ + allow: '/', + disallow, + userAgent: [ + ...aiAssistantAgents + ] + }); + aiRules.push({ + disallow: [ + '/' + ], + userAgent: [ + ...aiTrainingAgents + ] + }); + } else if (aiBots === 'disallow') { + aiRules.push({ + disallow: [ + '/' + ], + userAgent: [ + ...aiAssistantAgents, + ...aiTrainingAgents + ] + }); + } + return { + rules: aiRules.length > 0 ? [ + baseRule, + ...aiRules + ] : baseRule, ...sitemap ? { sitemap: `${origin}/sitemap.xml` } : {}, diff --git a/dist/modules/seo/buildRobots.js.map b/dist/modules/seo/buildRobots.js.map index e27a67b..6760039 100644 --- a/dist/modules/seo/buildRobots.js.map +++ b/dist/modules/seo/buildRobots.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/seo/buildRobots.ts"],"sourcesContent":["type BuildRobotsArgs = {\n /** Absolute origin, e.g. 'https://example.com'. */\n baseUrl: string\n /** Paths to disallow. Defaults to Payload's admin and API. */\n disallow?: string[]\n /** Whether to advertise the sitemap. Defaults to true. */\n sitemap?: boolean\n}\n\n/**\n * Shape for Next's `app/robots.ts`.\n */\nexport type RobotsRules = {\n host?: string\n rules: { allow?: string; disallow?: string[]; userAgent: string }\n sitemap?: string\n}\n\n/**\n * Builds robots rules that allow crawling everything except the admin panel and\n * API, and point crawlers at the sitemap.\n *\n * ```ts\n * // app/robots.ts\n * export default function robots() {\n * return buildRobots({ baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })\n * }\n * ```\n *\n * The admin and API are disallowed by default — no reason for them in the index,\n * and it keeps crawl budget on real content.\n */\nexport function buildRobots({\n baseUrl,\n disallow = ['/admin', '/api'],\n sitemap = true,\n}: BuildRobotsArgs): RobotsRules {\n const origin = baseUrl.replace(/\\/$/, '')\n\n return {\n rules: {\n allow: '/',\n disallow,\n userAgent: '*',\n },\n ...(sitemap ? { sitemap: `${origin}/sitemap.xml` } : {}),\n host: origin,\n }\n}\n"],"names":["buildRobots","baseUrl","disallow","sitemap","origin","replace","rules","allow","userAgent","host"],"mappings":"AAkBA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASA,YAAY,EAC1BC,OAAO,EACPC,WAAW;IAAC;IAAU;CAAO,EAC7BC,UAAU,IAAI,EACE;IAChB,MAAMC,SAASH,QAAQI,OAAO,CAAC,OAAO;IAEtC,OAAO;QACLC,OAAO;YACLC,OAAO;YACPL;YACAM,WAAW;QACb;QACA,GAAIL,UAAU;YAAEA,SAAS,GAAGC,OAAO,YAAY,CAAC;QAAC,IAAI,CAAC,CAAC;QACvDK,MAAML;IACR;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/seo/buildRobots.ts"],"sourcesContent":["type RobotRule = { allow?: string; disallow?: string[]; userAgent: string | string[] }\n\n/**\n * Known AI user agents, split by purpose:\n * - assistant/search bots fetch a page to answer a user's question live or to\n * power an AI search index — the ones that make \"the chat reads your site\"\n * work, and that most businesses WANT.\n * - training crawlers collect pages to train models — some clients prefer to\n * opt out of these while keeping assistant/search visibility.\n */\nexport const AI_ASSISTANT_BOTS = [\n 'ClaudeBot',\n 'Claude-Web',\n 'Claude-SearchBot',\n 'ChatGPT-User',\n 'OAI-SearchBot',\n 'PerplexityBot',\n 'Perplexity-User',\n] as const\n\nexport const AI_TRAINING_BOTS = [\n 'GPTBot',\n 'Google-Extended',\n 'CCBot',\n 'anthropic-ai',\n 'Applebot-Extended',\n 'Bytespider',\n 'Meta-ExternalAgent',\n] as const\n\ntype AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false\n\ntype BuildRobotsArgs = {\n /** Override the assistant/search bot list. */\n aiAssistantAgents?: readonly string[]\n /**\n * How to treat AI crawlers (assistant/search + training). Default 'allow' —\n * explicitly welcome them so the site stays visible to Claude, ChatGPT,\n * Perplexity etc. and an accidental future '*' tightening doesn't lock them\n * out. Options:\n * - 'allow' (default): explicit allow for assistant AND training bots.\n * - 'block-training': allow assistant/search bots, disallow training crawlers\n * — keep AI answers/visibility, opt out of model training.\n * - 'disallow': block all known AI bots.\n * - false: emit no AI-specific rules (only the '*' rule).\n */\n aiBots?: AiBotsPolicy\n /** Override the training crawler list. */\n aiTrainingAgents?: readonly string[]\n /** Absolute origin, e.g. 'https://example.com'. */\n baseUrl: string\n /** Paths to disallow. Defaults to Payload's admin and API. */\n disallow?: string[]\n /** Whether to advertise the sitemap. Defaults to true. */\n sitemap?: boolean\n}\n\n/**\n * Shape for Next's `app/robots.ts`. `rules` may be a single rule or an array\n * (Next accepts both) — it becomes an array when AI-bot rules are added.\n */\nexport type RobotsRules = {\n host?: string\n rules: RobotRule | RobotRule[]\n sitemap?: string\n}\n\n/**\n * Builds robots rules that allow crawling everything except the admin panel and\n * API, point crawlers at the sitemap, and (by default) explicitly welcome AI\n * assistant/search/training bots.\n *\n * ```ts\n * // app/robots.ts\n * export default function robots() {\n * return buildRobots({ baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })\n * }\n * ```\n *\n * The admin and API are disallowed by default — no reason for them in the index,\n * and it keeps crawl budget on real content.\n *\n * AI visibility: the #1 reason \"the chat won't read the site\" is an AI user\n * agent being blocked (or not explicitly allowed under a tightened '*' rule).\n * `aiBots: 'allow'` (default) emits explicit allow rules for ClaudeBot, GPTBot,\n * PerplexityBot, Google-Extended and friends. To keep AI answers but opt out of\n * model training, use `aiBots: 'block-training'`. To block them all, 'disallow'.\n *\n * Pass custom disallow to block parametrized/thin URLs that waste crawl budget:\n * ```ts\n * buildRobots({ baseUrl, disallow: ['/admin', '/api', '/*?meter=*', '/*?s=*'] })\n * ```\n */\nexport function buildRobots({\n aiAssistantAgents = AI_ASSISTANT_BOTS,\n aiBots = 'allow',\n aiTrainingAgents = AI_TRAINING_BOTS,\n baseUrl,\n disallow = ['/admin', '/api'],\n sitemap = true,\n}: BuildRobotsArgs): RobotsRules {\n const origin = baseUrl.replace(/\\/$/, '')\n\n const baseRule: RobotRule = { allow: '/', disallow, userAgent: '*' }\n\n const aiRules: RobotRule[] = []\n if (aiBots === 'allow') {\n aiRules.push({ allow: '/', disallow, userAgent: [...aiAssistantAgents, ...aiTrainingAgents] })\n } else if (aiBots === 'block-training') {\n aiRules.push({ allow: '/', disallow, userAgent: [...aiAssistantAgents] })\n aiRules.push({ disallow: ['/'], userAgent: [...aiTrainingAgents] })\n } else if (aiBots === 'disallow') {\n aiRules.push({ disallow: ['/'], userAgent: [...aiAssistantAgents, ...aiTrainingAgents] })\n }\n\n return {\n rules: aiRules.length > 0 ? [baseRule, ...aiRules] : baseRule,\n ...(sitemap ? { sitemap: `${origin}/sitemap.xml` } : {}),\n host: origin,\n }\n}\n"],"names":["AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildRobots","aiAssistantAgents","aiBots","aiTrainingAgents","baseUrl","disallow","sitemap","origin","replace","baseRule","allow","userAgent","aiRules","push","rules","length","host"],"mappings":"AAEA;;;;;;;CAOC,GACD,OAAO,MAAMA,oBAAoB;IAC/B;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS;AAEV,OAAO,MAAMC,mBAAmB;IAC9B;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS;AAuCV;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GACD,OAAO,SAASC,YAAY,EAC1BC,oBAAoBH,iBAAiB,EACrCI,SAAS,OAAO,EAChBC,mBAAmBJ,gBAAgB,EACnCK,OAAO,EACPC,WAAW;IAAC;IAAU;CAAO,EAC7BC,UAAU,IAAI,EACE;IAChB,MAAMC,SAASH,QAAQI,OAAO,CAAC,OAAO;IAEtC,MAAMC,WAAsB;QAAEC,OAAO;QAAKL;QAAUM,WAAW;IAAI;IAEnE,MAAMC,UAAuB,EAAE;IAC/B,IAAIV,WAAW,SAAS;QACtBU,QAAQC,IAAI,CAAC;YAAEH,OAAO;YAAKL;YAAUM,WAAW;mBAAIV;mBAAsBE;aAAiB;QAAC;IAC9F,OAAO,IAAID,WAAW,kBAAkB;QACtCU,QAAQC,IAAI,CAAC;YAAEH,OAAO;YAAKL;YAAUM,WAAW;mBAAIV;aAAkB;QAAC;QACvEW,QAAQC,IAAI,CAAC;YAAER,UAAU;gBAAC;aAAI;YAAEM,WAAW;mBAAIR;aAAiB;QAAC;IACnE,OAAO,IAAID,WAAW,YAAY;QAChCU,QAAQC,IAAI,CAAC;YAAER,UAAU;gBAAC;aAAI;YAAEM,WAAW;mBAAIV;mBAAsBE;aAAiB;QAAC;IACzF;IAEA,OAAO;QACLW,OAAOF,QAAQG,MAAM,GAAG,IAAI;YAACN;eAAaG;SAAQ,GAAGH;QACrD,GAAIH,UAAU;YAAEA,SAAS,GAAGC,OAAO,YAAY,CAAC;QAAC,IAAI,CAAC,CAAC;QACvDS,MAAMT;IACR;AACF"} \ No newline at end of file diff --git a/dist/modules/seo/buildSpeakableJsonLd.d.ts b/dist/modules/seo/buildSpeakableJsonLd.d.ts new file mode 100644 index 0000000..e6178db --- /dev/null +++ b/dist/modules/seo/buildSpeakableJsonLd.d.ts @@ -0,0 +1,39 @@ +type SpeakableJsonLdArgs = { + /** + * CSS selectors marking the parts best suited to be read aloud by voice + * assistants / AI (a summary, the lead paragraph, key answer). Default + * ['h1', '.speakable']. Keep it to genuinely readable, self-contained text — + * not nav or boilerplate. + */ + cssSelectors?: string[]; + /** Optional @id to join this node into a @graph (e.g. `${url}#webpage`). */ + id?: string; + /** Canonical URL of the page this describes. */ + url: string; +}; +/** + * Builds WebPage JSON-LD with a `speakable` SpeakableSpecification — tells voice + * assistants and AI which parts of the page are meant to be read aloud / + * quoted. A GEO signal: pairs with the Markdown/llms work to make the page's key + * content easy for assistants to lift cleanly. + * + * Add to the page's @graph via JsonLdGraph (recommended) or emit standalone: + * + * import { buildSpeakableJsonLd } from '@intecion/ipal-kit' + * const node = buildSpeakableJsonLd({ url: canonical, cssSelectors: ['h1', '.lead'] }) + * + * Mark the matching elements in the project markup (e.g. className="speakable" + * or a `.lead` summary). Selectors that match nothing are simply ignored by + * consumers — but don't point at nav/boilerplate. + */ +export declare function buildSpeakableJsonLd({ id, cssSelectors, url, }: SpeakableJsonLdArgs): { + speakable: { + '@type': string; + cssSelector: string[]; + }; + url: string; + '@id'?: string | undefined; + '@context': string; + '@type': string; +}; +export {}; diff --git a/dist/modules/seo/buildSpeakableJsonLd.js b/dist/modules/seo/buildSpeakableJsonLd.js new file mode 100644 index 0000000..01099fd --- /dev/null +++ b/dist/modules/seo/buildSpeakableJsonLd.js @@ -0,0 +1,33 @@ +/** + * Builds WebPage JSON-LD with a `speakable` SpeakableSpecification — tells voice + * assistants and AI which parts of the page are meant to be read aloud / + * quoted. A GEO signal: pairs with the Markdown/llms work to make the page's key + * content easy for assistants to lift cleanly. + * + * Add to the page's @graph via JsonLdGraph (recommended) or emit standalone: + * + * import { buildSpeakableJsonLd } from '@intecion/ipal-kit' + * const node = buildSpeakableJsonLd({ url: canonical, cssSelectors: ['h1', '.lead'] }) + * + * Mark the matching elements in the project markup (e.g. className="speakable" + * or a `.lead` summary). Selectors that match nothing are simply ignored by + * consumers — but don't point at nav/boilerplate. + */ export function buildSpeakableJsonLd({ id, cssSelectors = [ + 'h1', + '.speakable' +], url }) { + return { + '@context': 'https://schema.org', + '@type': 'WebPage', + ...id ? { + '@id': id + } : {}, + speakable: { + '@type': 'SpeakableSpecification', + cssSelector: cssSelectors + }, + url + }; +} + +//# sourceMappingURL=buildSpeakableJsonLd.js.map \ No newline at end of file diff --git a/dist/modules/seo/buildSpeakableJsonLd.js.map b/dist/modules/seo/buildSpeakableJsonLd.js.map new file mode 100644 index 0000000..e75e7a4 --- /dev/null +++ b/dist/modules/seo/buildSpeakableJsonLd.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/seo/buildSpeakableJsonLd.ts"],"sourcesContent":["type SpeakableJsonLdArgs = {\n /**\n * CSS selectors marking the parts best suited to be read aloud by voice\n * assistants / AI (a summary, the lead paragraph, key answer). Default\n * ['h1', '.speakable']. Keep it to genuinely readable, self-contained text —\n * not nav or boilerplate.\n */\n cssSelectors?: string[]\n /** Optional @id to join this node into a @graph (e.g. `${url}#webpage`). */\n id?: string\n /** Canonical URL of the page this describes. */\n url: string\n}\n\n/**\n * Builds WebPage JSON-LD with a `speakable` SpeakableSpecification — tells voice\n * assistants and AI which parts of the page are meant to be read aloud /\n * quoted. A GEO signal: pairs with the Markdown/llms work to make the page's key\n * content easy for assistants to lift cleanly.\n *\n * Add to the page's @graph via JsonLdGraph (recommended) or emit standalone:\n *\n * import { buildSpeakableJsonLd } from '@intecion/ipal-kit'\n * const node = buildSpeakableJsonLd({ url: canonical, cssSelectors: ['h1', '.lead'] })\n *\n * Mark the matching elements in the project markup (e.g. className=\"speakable\"\n * or a `.lead` summary). Selectors that match nothing are simply ignored by\n * consumers — but don't point at nav/boilerplate.\n */\nexport function buildSpeakableJsonLd({\n id,\n cssSelectors = ['h1', '.speakable'],\n url,\n}: SpeakableJsonLdArgs) {\n return {\n '@context': 'https://schema.org',\n '@type': 'WebPage',\n ...(id ? { '@id': id } : {}),\n speakable: {\n '@type': 'SpeakableSpecification',\n cssSelector: cssSelectors,\n },\n url,\n }\n}\n"],"names":["buildSpeakableJsonLd","id","cssSelectors","url","speakable","cssSelector"],"mappings":"AAcA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASA,qBAAqB,EACnCC,EAAE,EACFC,eAAe;IAAC;IAAM;CAAa,EACnCC,GAAG,EACiB;IACpB,OAAO;QACL,YAAY;QACZ,SAAS;QACT,GAAIF,KAAK;YAAE,OAAOA;QAAG,IAAI,CAAC,CAAC;QAC3BG,WAAW;YACT,SAAS;YACTC,aAAaH;QACf;QACAC;IACF;AACF"} \ No newline at end of file diff --git a/dist/modules/seo/buildSummaryField.d.ts b/dist/modules/seo/buildSummaryField.d.ts new file mode 100644 index 0000000..5607033 --- /dev/null +++ b/dist/modules/seo/buildSummaryField.d.ts @@ -0,0 +1,38 @@ +import type { Field, TextareaField } from 'payload'; +type BuildSummaryFieldArgs = { + /** Auto-fill from page content when the editor leaves it empty. Default true. */ + autoFill?: boolean; + /** Help text under the field. */ + description?: string; + /** Sidebar/admin label. */ + label?: string; + /** Block layout field to derive the summary from. Default 'layout'. */ + layoutField?: string; + /** Target length for the auto-generated summary. Default 300. */ + maxLength?: number; + /** Field name. Default 'aiSummary'. */ + name?: string; + /** Extend/override the generated textarea (position, access…). */ + overrides?: Partial; +}; +/** + * A localized `aiSummary` textarea — a concise, human-written (or auto-derived) + * description of the page, richer than the SEO meta description. It's the + * preferred description for AI-facing surfaces: pass `summaryField: 'aiSummary'` + * to buildLlmsTxt and searchContent and they'll use it over meta.description. + * + * With `autoFill` (default), an empty summary is filled on save from the page's + * own content (blocks → plain text, trimmed to ~maxLength). Editors can always + * overwrite it — auto-fill only runs when the field is blank, never clobbers a + * manual summary. Derived from the page's OWN content, so no hard-coded data. + * + * // collections/Pages.ts + * import { buildSummaryField } from '@intecion/ipal-kit' + * fields: [ /* … *\/ buildSummaryField() ] + * + * // then, richer AI descriptions: + * buildLlmsTxt({ …, summaryField: 'aiSummary' }) + * createSearchRoute({ …, summaryField: 'aiSummary' }) + */ +export declare function buildSummaryField(args?: BuildSummaryFieldArgs): Field; +export {}; diff --git a/dist/modules/seo/buildSummaryField.js b/dist/modules/seo/buildSummaryField.js new file mode 100644 index 0000000..81b1875 --- /dev/null +++ b/dist/modules/seo/buildSummaryField.js @@ -0,0 +1,77 @@ +import { blocksToMarkdown } from '../content/blocksToMarkdown.js'; +/** Rough Markdown → plain text, enough for a summary (drops syntax, keeps words). */ function mdToPlain(md) { + return md.replace(/!\[[^\]]*\]\([^)]*\)/g, '') // images + .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // links → their text + .replace(/^#{1,6}\s+/gm, '') // heading markers + .replace(/^[>\-*]\s+/gm, '') // quote/list markers + .replace(/[*_~`]/g, '') // inline emphasis/code marks + .replace(/\s+/g, ' ').trim(); +} +/** Truncate at a word boundary, adding an ellipsis when cut. */ function truncate(text, max) { + if (text.length <= max) { + return text; + } + const slice = text.slice(0, max); + const lastSpace = slice.lastIndexOf(' '); + return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`; +} +/** + * A localized `aiSummary` textarea — a concise, human-written (or auto-derived) + * description of the page, richer than the SEO meta description. It's the + * preferred description for AI-facing surfaces: pass `summaryField: 'aiSummary'` + * to buildLlmsTxt and searchContent and they'll use it over meta.description. + * + * With `autoFill` (default), an empty summary is filled on save from the page's + * own content (blocks → plain text, trimmed to ~maxLength). Editors can always + * overwrite it — auto-fill only runs when the field is blank, never clobbers a + * manual summary. Derived from the page's OWN content, so no hard-coded data. + * + * // collections/Pages.ts + * import { buildSummaryField } from '@intecion/ipal-kit' + * fields: [ /* … *\/ buildSummaryField() ] + * + * // then, richer AI descriptions: + * buildLlmsTxt({ …, summaryField: 'aiSummary' }) + * createSearchRoute({ …, summaryField: 'aiSummary' }) + */ export function buildSummaryField(args = {}) { + const { name = 'aiSummary', autoFill = true, description = 'Zwięzły opis strony dla agentów AI i llms.txt (bogatszy niż meta description). Puste → generowane automatycznie z treści.', label = 'Streszczenie dla AI', layoutField = 'layout', maxLength = 300, overrides = {} } = args; + const autofillHook = ({ data, value })=>{ + if (typeof value === 'string' && value.trim()) { + return value; + } // never clobber a manual summary + if (!data || typeof data !== 'object') { + return value; + } + const layout = data[layoutField]; + const md = blocksToMarkdown(layout); + if (!md) { + return value; + } + const plain = mdToPlain(md); + return plain ? truncate(plain, maxLength) : value; + }; + const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides; + return { + name, + type: 'textarea', + admin: { + description, + position: 'sidebar', + ...adminOverrides + }, + hooks: { + ...hooksOverrides, + ...autoFill ? { + beforeChange: [ + autofillHook, + ...hooksOverrides?.beforeChange ?? [] + ] + } : {} + }, + label, + localized: true, + ...restOverrides + }; +} + +//# sourceMappingURL=buildSummaryField.js.map \ No newline at end of file diff --git a/dist/modules/seo/buildSummaryField.js.map b/dist/modules/seo/buildSummaryField.js.map new file mode 100644 index 0000000..b092c84 --- /dev/null +++ b/dist/modules/seo/buildSummaryField.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/seo/buildSummaryField.ts"],"sourcesContent":["import type { Field, FieldHook, TextareaField } from 'payload'\n\nimport { blocksToMarkdown } from '../content/blocksToMarkdown.js'\n\ntype BuildSummaryFieldArgs = {\n /** Auto-fill from page content when the editor leaves it empty. Default true. */\n autoFill?: boolean\n /** Help text under the field. */\n description?: string\n /** Sidebar/admin label. */\n label?: string\n /** Block layout field to derive the summary from. Default 'layout'. */\n layoutField?: string\n /** Target length for the auto-generated summary. Default 300. */\n maxLength?: number\n /** Field name. Default 'aiSummary'. */\n name?: string\n /** Extend/override the generated textarea (position, access…). */\n overrides?: Partial\n}\n\n/** Rough Markdown → plain text, enough for a summary (drops syntax, keeps words). */\nfunction mdToPlain(md: string): string {\n return md\n .replace(/!\\[[^\\]]*\\]\\([^)]*\\)/g, '') // images\n .replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, '$1') // links → their text\n .replace(/^#{1,6}\\s+/gm, '') // heading markers\n .replace(/^[>\\-*]\\s+/gm, '') // quote/list markers\n .replace(/[*_~`]/g, '') // inline emphasis/code marks\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** Truncate at a word boundary, adding an ellipsis when cut. */\nfunction truncate(text: string, max: number): string {\n if (text.length <= max) {return text}\n const slice = text.slice(0, max)\n const lastSpace = slice.lastIndexOf(' ')\n return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`\n}\n\n/**\n * A localized `aiSummary` textarea — a concise, human-written (or auto-derived)\n * description of the page, richer than the SEO meta description. It's the\n * preferred description for AI-facing surfaces: pass `summaryField: 'aiSummary'`\n * to buildLlmsTxt and searchContent and they'll use it over meta.description.\n *\n * With `autoFill` (default), an empty summary is filled on save from the page's\n * own content (blocks → plain text, trimmed to ~maxLength). Editors can always\n * overwrite it — auto-fill only runs when the field is blank, never clobbers a\n * manual summary. Derived from the page's OWN content, so no hard-coded data.\n *\n * // collections/Pages.ts\n * import { buildSummaryField } from '@intecion/ipal-kit'\n * fields: [ /* … *\\/ buildSummaryField() ]\n *\n * // then, richer AI descriptions:\n * buildLlmsTxt({ …, summaryField: 'aiSummary' })\n * createSearchRoute({ …, summaryField: 'aiSummary' })\n */\nexport function buildSummaryField(args: BuildSummaryFieldArgs = {}): Field {\n const {\n name = 'aiSummary',\n autoFill = true,\n description = 'Zwięzły opis strony dla agentów AI i llms.txt (bogatszy niż meta description). Puste → generowane automatycznie z treści.',\n label = 'Streszczenie dla AI',\n layoutField = 'layout',\n maxLength = 300,\n overrides = {},\n } = args\n\n const autofillHook: FieldHook = ({ data, value }) => {\n if (typeof value === 'string' && value.trim()) {return value} // never clobber a manual summary\n if (!data || typeof data !== 'object') {return value}\n const layout = (data as Record)[layoutField]\n const md = blocksToMarkdown(layout)\n if (!md) {return value}\n const plain = mdToPlain(md)\n return plain ? truncate(plain, maxLength) : value\n }\n\n const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides\n\n return {\n name,\n type: 'textarea',\n admin: {\n description,\n position: 'sidebar',\n ...adminOverrides,\n },\n hooks: {\n ...hooksOverrides,\n ...(autoFill\n ? { beforeChange: [autofillHook, ...(hooksOverrides?.beforeChange ?? [])] }\n : {}),\n },\n label,\n localized: true,\n ...restOverrides,\n } as TextareaField\n}\n"],"names":["blocksToMarkdown","mdToPlain","md","replace","trim","truncate","text","max","length","slice","lastSpace","lastIndexOf","trimEnd","buildSummaryField","args","name","autoFill","description","label","layoutField","maxLength","overrides","autofillHook","data","value","layout","plain","admin","adminOverrides","hooks","hooksOverrides","restOverrides","type","position","beforeChange","localized"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,iCAAgC;AAmBjE,mFAAmF,GACnF,SAASC,UAAUC,EAAU;IAC3B,OAAOA,GACJC,OAAO,CAAC,yBAAyB,IAAI,SAAS;KAC9CA,OAAO,CAAC,0BAA0B,MAAM,qBAAqB;KAC7DA,OAAO,CAAC,gBAAgB,IAAI,kBAAkB;KAC9CA,OAAO,CAAC,gBAAgB,IAAI,qBAAqB;KACjDA,OAAO,CAAC,WAAW,IAAI,6BAA6B;KACpDA,OAAO,CAAC,QAAQ,KAChBC,IAAI;AACT;A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AkBQ,gBAAgBI,gBAAgB,EAAE;iBAAE;YAAC,IACxE,CAAC,CAAC;QACR;QACAhB;QACAiB,WAAW;QACX,GAAGJ,aAAa;IAClB;AACF"} \ No newline at end of file diff --git a/dist/modules/seo/index.d.ts b/dist/modules/seo/index.d.ts index 237d1cb..8c7e3c8 100644 --- a/dist/modules/seo/index.d.ts +++ b/dist/modules/seo/index.d.ts @@ -11,13 +11,15 @@ export { buildMetadata } from './buildMetadata.js'; export type { PageMetadata } from './buildMetadata.js'; export { buildNoindexField } from './buildNoindexField.js'; export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'; -export { buildRobots } from './buildRobots.js'; +export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'; export type { RobotsRules } from './buildRobots.js'; export { buildServiceJsonLd } from './buildServiceJsonLd.js'; export { buildSitemapEntries } from './buildSitemapEntries.js'; export type { SitemapEntry } from './buildSitemapEntries.js'; export { buildSitemapXml } from './buildSitemapXml.js'; export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'; +export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'; +export { buildSummaryField } from './buildSummaryField.js'; export { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'; export { composeTitle } from './composeTitle.js'; export type { TitleOrder } from './composeTitle.js'; diff --git a/dist/modules/seo/index.js b/dist/modules/seo/index.js index 4c83be4..1c9b8ce 100644 --- a/dist/modules/seo/index.js +++ b/dist/modules/seo/index.js @@ -9,11 +9,13 @@ export { createManifestHandler } from './buildManifest.js'; export { buildMetadata } from './buildMetadata.js'; export { buildNoindexField } from './buildNoindexField.js'; export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'; -export { buildRobots } from './buildRobots.js'; +export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'; export { buildServiceJsonLd } from './buildServiceJsonLd.js'; export { buildSitemapEntries } from './buildSitemapEntries.js'; export { buildSitemapXml } from './buildSitemapXml.js'; export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'; +export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'; +export { buildSummaryField } from './buildSummaryField.js'; export { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'; export { composeTitle } from './composeTitle.js'; export { createMetadataGenerator } from './createMetadataGenerator.js'; diff --git a/dist/modules/seo/index.js.map b/dist/modules/seo/index.js.map index dc2a66b..e6bd885 100644 --- a/dist/modules/seo/index.js.map +++ b/dist/modules/seo/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildNoindexField } from './buildNoindexField.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildNoindexField","buildOrganizationJsonLd","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildNoindexField } from './buildNoindexField.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'\nexport { buildSummaryField } from './buildSummaryField.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildNoindexField","buildOrganizationJsonLd","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildSpeakableJsonLd","buildSummaryField","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcross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dist/modules/seo/routeHandlers.d.ts index 09c52b9..41182a4 100644 --- a/dist/modules/seo/routeHandlers.d.ts +++ b/dist/modules/seo/routeHandlers.d.ts @@ -13,13 +13,23 @@ import type { SitemapEntry } from './buildSitemapEntries.js'; * export const dynamic = 'force-dynamic' * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig, * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! }) + * + * For the full-content variant, add a second route with `full: true`: + * + * // app/llms-full.txt/route.ts + * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig, + * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, full: true }) */ export declare function createLlmsTxtRoute(opts: { baseUrl: string; config: I18nConfig; + /** Inline every page's full Markdown (llms-full.txt). Default false. */ + full?: boolean; getCachedPayload: () => Promise; pagesSlug?: string; settingsSlug?: string; + /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */ + summaryField?: string; }): () => Promise; /** * Ready-made Next route handler for /sitemap.xml with the CSS stylesheet. diff --git a/dist/modules/seo/routeHandlers.js b/dist/modules/seo/routeHandlers.js index 04fdfa6..614f82d 100644 --- a/dist/modules/seo/routeHandlers.js +++ b/dist/modules/seo/routeHandlers.js @@ -12,6 +12,12 @@ import { buildSitemapXml } from './buildSitemapXml.js'; * export const dynamic = 'force-dynamic' * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig, * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! }) + * + * For the full-content variant, add a second route with `full: true`: + * + * // app/llms-full.txt/route.ts + * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig, + * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, full: true }) */ export function createLlmsTxtRoute(opts) { return async ()=>{ try { @@ -19,9 +25,11 @@ import { buildSitemapXml } from './buildSitemapXml.js'; const body = await buildLlmsTxt({ baseUrl: opts.baseUrl, config: opts.config, + full: opts.full, pagesSlug: opts.pagesSlug, payload, - settingsSlug: opts.settingsSlug + settingsSlug: opts.settingsSlug, + summaryField: opts.summaryField }); return new Response(body, { headers: { diff --git a/dist/modules/seo/routeHandlers.js.map b/dist/modules/seo/routeHandlers.js.map index 8448dd8..9dbe65f 100644 --- a/dist/modules/seo/routeHandlers.js.map +++ b/dist/modules/seo/routeHandlers.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/seo/routeHandlers.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\nimport type { SitemapEntry } from './buildSitemapEntries.js'\n\nimport { buildLlmsTxt } from './buildLlmsTxt.js'\nimport { buildSitemapXml } from './buildSitemapXml.js'\n\n/**\n * Ready-made Next route handler for /llms.txt. Replaces the ~60-line try/catch\n * every project was copying. buildLlmsTxt already handles collections without\n * drafts, so no workaround is needed here.\n *\n * // app/llms.txt/route.ts\n * import { createLlmsTxtRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })\n */\nexport function createLlmsTxtRoute(opts: {\n baseUrl: string\n config: I18nConfig\n getCachedPayload: () => Promise\n pagesSlug?: string\n settingsSlug?: string\n}): () => Promise {\n return async () => {\n try {\n const payload = await opts.getCachedPayload()\n const body = await buildLlmsTxt({\n baseUrl: opts.baseUrl,\n config: opts.config,\n pagesSlug: opts.pagesSlug,\n payload,\n settingsSlug: opts.settingsSlug,\n })\n return new Response(body, {\n headers: { 'Content-Type': 'text/plain; charset=utf-8' },\n })\n } catch (err) {\n // DB unreachable at build (container) — return a minimal valid file so the\n // route doesn't 500; it fills in at runtime. No per-project try/catch.\n console.warn('[ipal] createLlmsTxtRoute: could not build llms.txt:', err)\n return new Response('# llms.txt\\n', {\n headers: { 'Content-Type': 'text/plain; charset=utf-8' },\n })\n }\n }\n}\n\n/**\n * Ready-made Next route handler for /sitemap.xml with the CSS stylesheet.\n * Replaces the hand-written route in every project. Pass the project's `sitemap`\n * helper (from createContentHelpers) and optionally a cssUrl.\n *\n * // app/sitemap.xml/route.ts\n * import { createSitemapRouteHandler } from '@intecion/ipal-kit'\n * import { sitemap } from '@/lib/content'\n * export const dynamic = 'force-dynamic'\n * export const GET = createSitemapRouteHandler(sitemap, { cssUrl: '/sitemap.css' })\n *\n * Remember: if you use this, DON'T also keep app/sitemap.ts (two sitemaps\n * confuse crawlers).\n */\nexport function createSitemapRouteHandler(\n sitemap: () => Promise,\n opts: { cssUrl?: string } = {},\n): () => Promise {\n return async () => {\n try {\n const entries = await sitemap()\n const xml = buildSitemapXml(entries, { cssUrl: opts.cssUrl })\n return new Response(xml, {\n headers: { 'Content-Type': 'application/xml; charset=utf-8' },\n })\n } catch (err) {\n console.warn('[ipal] createSitemapRouteHandler: could not build sitemap:', err)\n // Valid empty urlset so the route doesn't 500 during a DB-less build.\n const empty =\n '\\n' +\n ''\n return new Response(empty, {\n headers: { 'Content-Type': 'application/xml; charset=utf-8' },\n })\n }\n }\n}\n"],"names":["buildLlmsTxt","buildSitemapXml","createLlmsTxtRoute","opts","payload","getCachedPayload","body","baseUrl","config","pagesSlug","settingsSlug","Response","headers","err","console","warn","createSitemapRouteHandler","sitemap","entries","xml","cssUrl","empty"],"mappings":"AAKA,SAASA,YAAY,QAAQ,oBAAmB;AAChD,SAASC,eAAe,QAAQ,uBAAsB;AAEtD;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,mBAAmBC,IAMlC;IACC,OAAO;QACL,IAAI;YACF,MAAMC,UAAU,MAAMD,KAAKE,gBAAgB;YAC3C,MAAMC,OAAO,MAAMN,aAAa;gBAC9BO,SAASJ,KAAKI,OAAO;gBACrBC,QAAQL,KAAKK,MAAM;gBACnBC,WAAWN,KAAKM,SAAS;gBACzBL;gBACAM,cAAcP,KAAKO,YAAY;YACjC;YACA,OAAO,IAAIC,SAASL,MAAM;gBACxBM,SAAS;oBAAE,gBAAgB;gBAA4B;YACzD;QACF,EAAE,OAAOC,KAAK;YACZ,2EAA2E;YAC3E,uEAAuE;YACvEC,QAAQC,IAAI,CAAC,wDAAwDF;YACrE,OAAO,IAAIF,SAAS,gBAAgB;gBAClCC,SAAS;oBAAE,gBAAgB;gBAA4B;YACzD;QACF;IACF;AACF;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASI,0BACdC,OAAsC,EACtCd,OAA4B,CAAC,CAAC;IAE9B,OAAO;QACL,IAAI;YACF,MAAMe,UAAU,MAAMD;YACtB,MAAME,MAAMlB,gBAAgBiB,SAAS;gBAAEE,QAAQjB,KAAKiB,MAAM;YAAC;YAC3D,OAAO,IAAIT,SAASQ,KAAK;gBACvBP,SAAS;oBAAE,gBAAgB;gBAAiC;YAC9D;QACF,EAAE,OAAOC,KAAK;YACZC,QAAQC,IAAI,CAAC,8DAA8DF;YAC3E,sEAAsE;YACtE,MAAMQ,QACJ,6CACA;YACF,OAAO,IAAIV,SAASU,OAAO;gBACzBT,SAAS;oBAAE,gBAAgB;gBAAiC;YAC9D;QACF;IACF;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/seo/routeHandlers.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\nimport type { SitemapEntry } from './buildSitemapEntries.js'\n\nimport { buildLlmsTxt } from './buildLlmsTxt.js'\nimport { buildSitemapXml } from './buildSitemapXml.js'\n\n/**\n * Ready-made Next route handler for /llms.txt. Replaces the ~60-line try/catch\n * every project was copying. buildLlmsTxt already handles collections without\n * drafts, so no workaround is needed here.\n *\n * // app/llms.txt/route.ts\n * import { createLlmsTxtRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })\n *\n * For the full-content variant, add a second route with `full: true`:\n *\n * // app/llms-full.txt/route.ts\n * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, full: true })\n */\nexport function createLlmsTxtRoute(opts: {\n baseUrl: string\n config: I18nConfig\n /** Inline every page's full Markdown (llms-full.txt). Default false. */\n full?: boolean\n getCachedPayload: () => Promise\n pagesSlug?: string\n settingsSlug?: string\n /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */\n summaryField?: string\n}): () => Promise {\n return async () => {\n try {\n const payload = await opts.getCachedPayload()\n const body = await buildLlmsTxt({\n baseUrl: opts.baseUrl,\n config: opts.config,\n full: opts.full,\n pagesSlug: opts.pagesSlug,\n payload,\n settingsSlug: opts.settingsSlug,\n summaryField: opts.summaryField,\n })\n return new Response(body, {\n headers: { 'Content-Type': 'text/plain; charset=utf-8' },\n })\n } catch (err) {\n // DB unreachable at build (container) — return a minimal valid file so the\n // route doesn't 500; it fills in at runtime. No per-project try/catch.\n console.warn('[ipal] createLlmsTxtRoute: could not build llms.txt:', err)\n return new Response('# llms.txt\\n', {\n headers: { 'Content-Type': 'text/plain; charset=utf-8' },\n })\n }\n }\n}\n\n/**\n * Ready-made Next route handler for /sitemap.xml with the CSS stylesheet.\n * Replaces the hand-written route in every project. Pass the project's `sitemap`\n * helper (from createContentHelpers) and optionally a cssUrl.\n *\n * // app/sitemap.xml/route.ts\n * import { createSitemapRouteHandler } from '@intecion/ipal-kit'\n * import { sitemap } from '@/lib/content'\n * export const dynamic = 'force-dynamic'\n * export const GET = createSitemapRouteHandler(sitemap, { cssUrl: '/sitemap.css' })\n *\n * Remember: if you use this, DON'T also keep app/sitemap.ts (two sitemaps\n * confuse crawlers).\n */\nexport function createSitemapRouteHandler(\n sitemap: () => Promise,\n opts: { cssUrl?: string } = {},\n): () => Promise {\n return async () => {\n try {\n const entries = await sitemap()\n const xml = buildSitemapXml(entries, { cssUrl: opts.cssUrl })\n return new Response(xml, {\n headers: { 'Content-Type': 'application/xml; charset=utf-8' },\n })\n } catch (err) {\n console.warn('[ipal] createSitemapRouteHandler: could not build sitemap:', err)\n // Valid empty urlset so the route doesn't 500 during a DB-less build.\n const empty =\n '\\n' +\n ''\n return new Response(empty, {\n headers: { 'Content-Type': 'application/xml; charset=utf-8' },\n })\n }\n }\n}\n"],"names":["buildLlmsTxt","buildSitemapXml","createLlmsTxtRoute","opts","payload","getCachedPayload","body","baseUrl","config","full","pagesSlug","settingsSlug","summaryField","Response","headers","err","console","warn","createSitemapRouteHandler","sitemap","entries","xml","cssUrl","empty"],"mappings":"AAKA,SAASA,YAAY,QAAQ,oBAAmB;AAChD,SAASC,eAAe,QAAQ,uBAAsB;AAEtD;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASC,mBAAmBC,IAUlC;IACC,OAAO;QACL,IAAI;YACF,MAAMC,UAAU,MAAMD,KAAKE,gBAAgB;YAC3C,MAAMC,OAAO,MAAMN,aAAa;gBAC9BO,SAASJ,KAAKI,OAAO;gBACrBC,QAAQL,KAAKK,MAAM;gBACnBC,MAAMN,KAAKM,IAAI;gBACfC,WAAWP,KAAKO,SAAS;gBACzBN;gBACAO,cAAcR,KAAKQ,YAAY;gBAC/BC,cAAcT,KAAKS,YAAY;YACjC;YACA,OAAO,IAAIC,SAASP,MAAM;gBACxBQ,SAAS;oBAAE,gBAAgB;gBAA4B;YACzD;QACF,EAAE,OAAOC,KAAK;YACZ,2EAA2E;YAC3E,uEAAuE;YACvEC,QAAQC,IAAI,CAAC,wDAAwDF;YACrE,OAAO,IAAIF,SAAS,gBAAgB;gBAClCC,SAAS;oBAAE,gBAAgB;gBAA4B;YACzD;QACF;IACF;AACF;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASI,0BACdC,OAAsC,EACtChB,OAA4B,CAAC,CAAC;IAE9B,OAAO;QACL,IAAI;YACF,MAAMiB,UAAU,MAAMD;YACtB,MAAME,MAAMpB,gBAAgBmB,SAAS;gBAAEE,QAAQnB,KAAKmB,MAAM;YAAC;YAC3D,OAAO,IAAIT,SAASQ,KAAK;gBACvBP,SAAS;oBAAE,gBAAgB;gBAAiC;YAC9D;QACF,EAAE,OAAOC,KAAK;YACZC,QAAQC,IAAI,CAAC,8DAA8DF;YAC3E,sEAAsE;YACtE,MAAMQ,QACJ,6CACA;YACF,OAAO,IAAIV,SAASU,OAAO;gBACzBT,SAAS;oBAAE,gBAAgB;gBAAiC;YAC9D;QACF;IACF;AACF"} \ No newline at end of file diff --git a/docs/README.md b/docs/README.md index e1a8871..3f3efee 100644 --- a/docs/README.md +++ b/docs/README.md @@ -106,6 +106,7 @@ export default buildConfig({ | i18n | Lokalizacja, negocjacja locale, ścieżki URL, strona jednojęzyczna | [i18n.md](./i18n.md) | | hooks | Hooki: revalidate ISR, slug history, cross-locale sync, noindex, ochrona | [hooks.md](./hooks.md) | | env | Walidacja zmiennych środowiskowych na starcie (assertEnv, fail fast) | [env.md](./env.md) | +| mcp | Read-only serwer MCP strony — Claude/agent podłącza się i odpytuje treść | [mcp.md](./mcp.md) | | kolekcje-katalog | Jakie kolekcje budować, kiedy, jak wpiąć (minimum nie maksimum) | [kolekcje-katalog.md](./kolekcje-katalog.md) | | fundamenty-projektu | Struktura katalogów, nazewnictwo, konwencje | [fundamenty-projektu.md](./fundamenty-projektu.md) | | deployment | Zmienne .env, ISR/SSG, force-dynamic, Coolify/Docker | [deployment.md](./deployment.md) | diff --git a/docs/agents-template.md b/docs/agents-template.md index b9810ed..67c75fb 100644 --- a/docs/agents-template.md +++ b/docs/agents-template.md @@ -250,6 +250,8 @@ Ten plik to skondensowane reguły. Szczegóły w `node_modules/@intecion/ipal-ki | Hooki (revalidate, slug history, cross-locale sync, ochrona) | `hooks.md` | | Redirecty 301/308 (resolveRedirect) | `content.md` | | Walidacja ENV na starcie (assertEnv) | `env.md` | +| Czytelność dla AI: Markdown per strona, llms-full, boty AI w robots | `content.md`, `seo.md` | +| Serwer MCP strony (Claude podłącza się do treści) | `mcp.md` | | Bezpieczeństwo, CSP, COOP | `security.md` | | Formularze, Turnstile, submitForm, useForm/useContactForm | `forms.md`, `turnstile.md` | | i18n, strona jednojęzyczna, ścieżki | `i18n.md` | diff --git a/docs/content.md b/docs/content.md index e30bab3..04ea69e 100644 --- a/docs/content.md +++ b/docs/content.md @@ -221,12 +221,129 @@ Ograniczenia: tylko kolekcje „płaskie" (slug → ścieżka). Wpisy w archiwac (`/artykuly/`) nie są jeszcze obsługiwane. Jeśli `slug` jest `localized`, rozważ `slugHistory` też `localized`, by historie języków się nie nakładały. +## Markdown per strona — czytelność dla AI (GEO) + +Agenci (WebFetch Claude'a, GPT, Perplexity) czytają stronę rzetelnie, gdy dostają +czysty Markdown zamiast parsować HTML. `createMarkdownRenderer` renderuje stronę +(tytuł + meta description + `blocks`) do Markdown; wpinasz go w route, który +serwuje np. `/md/pl/o-nas`: + +```ts +// app/md/[locale]/[[...slug]]/route.ts +import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit' +import { getPayload } from 'payload' +import config from '@payload-config' + +const render = createMarkdownRenderer({ content }) // content = ta sama opcja co w pluginie +export const dynamic = 'force-dynamic' + +export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) { + const { locale, slug } = await params + const md = await render({ payload: await getPayload({ config }), locale, slug }) + return markdownResponse(md) // text/markdown albo 404 +} +``` + +Jak to działa pod spodem: +- **`blocksToMarkdown(layout)`** — ekstrakcja po KONWENCJI nazw pól (heading→`##`, + subheading→`###`, body/content→tekst/richtext, image→`![]()`, tablice + items/faq/… rekurencyjnie). Pola nawigacyjne (ctaTarget, id, slug) są pomijane. + Bloki nietypowe: `overrides` per blockType. +- **`lexicalToMarkdown(data)`** — konwerter pojedynczego pola richText (bold, kursywa, + linki, listy, cytaty, obrazy). Samodzielny, bez zależności od eksportu MD Payloada + (odporny na bump wersji). Szczegóły: [richtext.md](./richtext.md). + +```ts +blocksToMarkdown(page.layout, { + overrides: { gallery: (b) => `(${(b.images as unknown[])?.length ?? 0} zdjęć)` }, +}) +``` + +Opcje `createMarkdownRenderer`: `content`, `collection` (`'pages'`), +`settingsSlug`, `layoutField` (`'layout'`), `overrides`, `frontmatter` +(domyślnie true — dokłada blok YAML title/description/locale). + +Komplet pod AI: ten endpoint + `llms.txt` (patrz [seo.md](./seo.md)) + wpuszczenie +botów w robots.txt. + +### Wykrywalność i negocjacja treści + +Żeby agent WIEDZIAŁ o wersji Markdown, ogłoś ją w `` strony jako alternatę +(`markdownHref` trzyma prefiks `/md` w jednym miejscu): + +```ts +// generateMetadata strony +import { markdownHref } from '@intecion/ipal-kit' +return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } } +// → +``` + +Opcjonalnie: ten sam URL serwuje Markdown przy negocjacji nagłówkiem `Accept` +(rewrite w proxy): + +```ts +// proxy.ts +import { prefersMarkdown, markdownHref } from '@intecion/ipal-kit' +if (prefersMarkdown(request)) { + return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url)) +} +``` + +`prefersMarkdown` respektuje q-values (wyżej ważony `text/html` wygrywa). Prefiks +zmienisz drugim argumentem `markdownHref(path, '/ai')` — pamiętaj wtedy o tym +samym w nazwie katalogu route'a. + +## Wyszukiwanie treści — searchContent / createSearchRoute + +Jedna logika wyszukiwania (po `title` i `meta.description`) zasila i wyszukiwarkę +na stronie, i agentów, i narzędzie `search_content` serwera MCP — to samo +rankowanie wszędzie. `createSearchRoute` wystawia endpoint JSON: + +```ts +// app/api/search/route.ts +import { createSearchRoute } from '@intecion/ipal-kit' +import { getCachedPayload } from '@/lib/content' +import { i18nConfig } from '@/i18n.config' +export const dynamic = 'force-dynamic' +export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig, + baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! }) +``` + +Query: `?q=` (wymagane), `?locale=`, `?limit=`. Odpowiedź: +```json +{ "query": "nas", "locale": "pl", "count": 1, + "results": [{ "title": "O nas", "url": "https://x/pl/o-nas", "description": "…", "slug": "o-nas" }] } +``` + +Brak `q` → 400. Tylko opublikowane, bez `noindex`. Błąd/baza offline → pusty +wynik (200), nie 500. Niska wartość `s-maxage` (60s) — wyniki świeże, ale z +cache'em CDN. + +Sam helper (do własnej wyszukiwarki po stronie serwera): +```ts +import { searchContent } from '@intecion/ipal-kit' +const results = await searchContent({ payload, query, config, locale, limit, baseUrl }) +// SearchResult[] = { title, url, description?, slug }[] +``` + +Opcje: `collection` (`'pages'`), `baseUrl`, `homeSlug`, `defaultLimit` (10, max +50), `summaryField` (np. `'aiSummary'` — preferuje bogatszy opis z +`buildSummaryField` nad `meta.description`; patrz [seo.md](./seo.md)). + ## Eksport ```ts import { resolveRoute, resolveRedirect, + blocksToMarkdown, + createMarkdownRenderer, + markdownResponse, + prefersMarkdown, + markdownHref, + searchContent, + createSearchRoute, + lexicalToMarkdown, getArchiveEntries, buildArchivePath, buildEntryPath, diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 0000000..92863b3 --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,75 @@ +# mcp — read-only serwer MCP strony + +`createMcpRoute` wystawia stronę klienta jako serwer **MCP (Model Context +Protocol)** — czyli Claude / dowolny klient MCP może się **podłączyć** do strony +i odpytywać ją bezpośrednio (wyszukać treść, pobrać stronę jako Markdown), +zamiast scrapować HTML. To warstwa „lepszej integracji" na wierzchu Markdown/llms. + +Powiązane: [content.md](./content.md) (Markdown per strona), [seo.md](./seo.md) +(llms.txt, robots). + +## Dlaczego bez SDK + +Plugin NIE wciąga `@modelcontextprotocol/sdk` — to byłaby narzucona zależność +(A0), a jej API się zmienia. `createMcpRoute` implementuje minimalną powierzchnię +JSON-RPC, jakiej potrzebuje read-only serwer po transporcie Streamable HTTP: +`initialize`, `tools/list`, `tools/call`, `ping`. Globalne `Request`/`Response`, +bez importu `next/server`. + +## Narzędzia + +| Narzędzie | Argumenty | Zwraca | +|-----------|-----------|--------| +| `search_content` | `query` (wymagane), `locale?`, `limit?` (domyślnie 10, max 50) | lista stron: tytuł, URL, opis | +| `get_page` | `path` (np. `/pl/o-nas`) | strona jako czysty Markdown | + +Oba **read-only** i tylko **opublikowane** treści (drafty i `meta.noindex` +odfiltrowane — ta sama zasada co sitemap/llms). + +## Wpięcie + +```ts +// app/api/mcp/route.ts +import { createMcpRoute } from '@intecion/ipal-kit' +import { getCachedPayload } from '@/lib/content' +import { i18nConfig } from '@/i18n.config' + +export const dynamic = 'force-dynamic' + +const mcp = createMcpRoute({ + getCachedPayload, + config: i18nConfig, + baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, + serverName: 'acme-site', // nazwa w initialize + // content, // jeśli masz kolekcje-archiwa (get_page dla wpisów) +}) + +export const POST = mcp.POST +export const GET = mcp.GET // 405 — brak strumienia SSE (request/response only) +``` + +## Podłączenie w Claude + +Dodaj jako custom connector wskazujący na `https://twoja-strona/api/mcp`. Claude +wykona `initialize` → `tools/list` → i będzie mógł wołać `search_content` / +`get_page`. Od tej chwili „zna" stronę bez scrapowania. + +## Opcje + +`getCachedPayload`, `config` (wymagane); `baseUrl` (URL-e w wynikach), `collection` +(`'pages'`), `settingsSlug`, `content` (kolekcje-archiwa dla `get_page`), +`serverName` (`'ipal-site'`), `serverVersion` (`'1.0.0'`). + +## Bezpieczeństwo + +- Tylko odczyt, tylko opublikowane treści — żadnych mutacji, żadnych draftów. +- `search_content` używa `like` i odpada bezpiecznie (komunikat), gdy pole nie + jest odpytywalne — nie wywala route'a. +- Nie wystawiaj tu niczego spoza publicznej treści strony. + +## Protokół (dla debugowania) + +Pojedynczy obiekt JSON-RPC albo batch (tablica). Notyfikacje (`notifications/*`, +bez `id`) → HTTP 202 bez ciała. Żądania → `{ jsonrpc:'2.0', id, result }` albo +`error` (`-32601` nieznana metoda, `-32700` parse error). `initialize` odbija +`protocolVersion` klienta (fallback `2025-06-18`). \ No newline at end of file diff --git a/docs/richtext.md b/docs/richtext.md index 2eb3640..d900ef7 100644 --- a/docs/richtext.md +++ b/docs/richtext.md @@ -53,6 +53,26 @@ const converters: JSXConvertersFunction = ({ defaultConverters }) => ({ Spread `defaultConverters` — nadpisujesz tylko te węzły, które chcesz. Reszta (listy, tabele, obrazy, linki) działa z oficjalnej obsługi Payload. +## lexicalToMarkdown — richText → Markdown (dla AI) + +Do czytelności dla agentów AI (Markdown per strona, llms-full) potrzebny jest +tekst, nie JSX. `lexicalToMarkdown` konwertuje pole richText na czysty Markdown: + +```ts +import { lexicalToMarkdown } from '@intecion/ipal-kit' +const md = lexicalToMarkdown(page.content) // '## Nagłówek\n\nAkapit **bold**…' +``` + +Obsługuje nagłówki, akapity, bold/kursywa/kod/strikethrough, linki, listy +(zagnieżdżone), cytaty, `---`, obrazy (upload). To tekstowy brat `RenderRichText` +— ten sam wejściowy kształt, inne wyjście. **Samodzielny walker**, NIE zależy od +konkretnego eksportu MD z `@payloadcms/richtext-lexical` (te zmieniają się między +wersjami), więc bump Payloada go nie zepsuje. Nieznany węzeł degraduje się do +swojej treści, nie rzuca. + +Dla całej strony (bloki, nie pojedyncze pole) użyj `blocksToMarkdown` / +`createMarkdownRenderer` — patrz [content.md](./content.md). + ## Zależność Oficjalny konwerter jest częścią `@payloadcms/richtext-lexical`, które projekt diff --git a/docs/seo.md b/docs/seo.md index d7c2d9b..fefb207 100644 --- a/docs/seo.md +++ b/docs/seo.md @@ -928,7 +928,84 @@ pomija drafty i noindex. Poprawia widoczność w wyszukiwaniach AI (GEO — Generative Engine Optimization) i audytach „Agentic Browsing”. Wymaga wypełnionego siteDescription i sensownych meta.description stron -(inaczej llms.txt będzie ubogi). +(inaczej llms.txt będzie ubogi) — albo pola `aiSummary` (niżej), bogatszego niż +meta description. + +### buildSummaryField — streszczenie dla AI (bogatsze niż meta) + +Pole `aiSummary` (localized textarea) — zwięzły opis strony dla agentów, +bogatszy niż SEO-owe `meta.description`. Z `autoFill` (domyślnie) puste pole jest +uzupełniane przy zapisie z TREŚCI strony (bloki → tekst, przycięte do ~300 +znaków); redaktor może nadpisać, auto-fill nigdy nie kasuje ręcznego opisu. + +```ts +// collections/Pages.ts +import { buildSummaryField } from '@intecion/ipal-kit' +fields: [ /* … */ buildSummaryField() ] +``` + +Potem wskaż je jako źródło opisu dla AI (preferowane nad meta.description): + +```ts +buildLlmsTxt({ …, summaryField: 'aiSummary' }) +createLlmsTxtRoute({ …, summaryField: 'aiSummary' }) +createSearchRoute({ …, summaryField: 'aiSummary' }) +createMcpRoute({ …, summaryField: 'aiSummary' }) +``` + +Opcje `buildSummaryField`: `name` (`'aiSummary'`), `label`, `description`, +`maxLength` (300), `layoutField` (`'layout'`), `autoFill` (true), `overrides`. +Treść pochodzi z WŁASNEJ strony — zero hardkodu danych klienta. + +### llms-full.txt — pełna treść w jednym pliku + +`llms.txt` to spis; `llms-full.txt` to cała treść stron inline (konwencja +llmstxt.org) — agent dostaje całą stronę jednym żądaniem. Dołóż drugi route z +`full: true`: + +```ts +// app/llms-full.txt/route.ts +import { createLlmsTxtRoute } from '@intecion/ipal-kit' +import { getCachedPayload } from '@/lib/content' +import { i18nConfig } from '@/i18n.config' +export const dynamic = 'force-dynamic' +export const GET = createLlmsTxtRoute({ + getCachedPayload, config: i18nConfig, + baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, full: true, +}) +``` + +W trybie `full` każda opublikowana strona jest renderowana do Markdown przez +`blocksToMarkdown` (fetch depth 1, żeby obrazki się zpopulowały). Patrz +[content.md](./content.md) (Markdown per strona). + +## robots.txt — wpuść boty AI (żeby chat czytał stronę) + +Najczęstszy powód, że „chat nie czyta strony", to zablokowany albo niejawny UA +bota AI. `buildRobots` domyślnie (`aiBots: 'allow'`) jawnie wpuszcza boty +asystentów/wyszukiwania i trenujące: + +```ts +// app/robots.ts +import { buildRobots } from '@intecion/ipal-kit' +export default function robots() { + return buildRobots({ baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! }) +} +``` + +Tryby `aiBots`: +- `'allow'` (domyślny) — jawny allow dla asystentów i trenujących (ClaudeBot, + GPTBot, PerplexityBot, Google-Extended…). Chroni przed utratą widoczności AI, + gdyby reguła `*` kiedyś się zacieśniła. +- `'block-training'` — wpuszcza asystentów/wyszukiwanie (odpowiedzi AI, widoczność), + blokuje crawlery trenujące. Dla klientów, którzy chcą być w AI, ale nie w + treningu modeli. +- `'disallow'` — blokuje wszystkie znane boty AI. +- `false` — bez reguł AI (tylko `*`). + +Listy botów: `AI_ASSISTANT_BOTS`, `AI_TRAINING_BOTS` (eksportowane; nadpisujesz +przez `aiAssistantAgents` / `aiTrainingAgents`). `Next` akceptuje `rules` jako +tablicę — przy aktywnych botach AI zwracana jest tablica reguł. ## Sitemap czytelny w przeglądarce (czysty XML) @@ -1031,4 +1108,25 @@ projekt miałby martwe pole NIP i brakujący ABN. Dlatego: danych na właściwy `@type` (LegalService w PL, HVACBusiness w AU) To eliminuje JEDYNE realne powielenie (opakowanie @graph + script, ~20 linii), -zostawiając model danych projektowi (gdzie jego miejsce). \ No newline at end of file +zostawiając model danych projektowi (gdzie jego miejsce). + +## speakable JSON-LD — fragmenty do czytania przez AI/głos + +`buildSpeakableJsonLd` oznacza, które części strony najlepiej nadają się do +odczytania na głos / zacytowania przez asystentów AI (sygnał GEO). Dokładasz węzeł +do `@graph`: + +```tsx +import { JsonLdGraph, buildSpeakableJsonLd } from '@intecion/ipal-kit' + +const speakable = buildSpeakableJsonLd({ + url: canonical, + cssSelectors: ['h1', '.lead'], // domyślnie ['h1', '.speakable'] +}) + +``` + +W markupie projektu oznacz pasujące elementy (np. `className="speakable"` albo +sekcja `.lead` ze streszczeniem). Selektory nietrafiające w nic są ignorowane — +nie wskazuj nawigacji ani boilerplate'u, tylko samodzielny, czytelny tekst. +Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony. \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 81a0727..c79a029 100644 --- a/src/index.ts +++ b/src/index.ts @@ -45,14 +45,23 @@ export type { } from './modules/content/index.js' export { archiveFieldName, + blocksToMarkdown, buildArchivePath, buildEntryPath, + createMarkdownRenderer, + createSearchRoute, getArchiveEntries, + MARKDOWN_PREFIX, + markdownHref, + markdownResponse, parsePageParam, + prefersMarkdown, resolveRedirect, resolveRoute, + searchContent, } from './modules/content/index.js' export 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' @@ -116,6 +125,8 @@ 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' +// 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, @@ -133,6 +144,8 @@ export { 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' export { buildSecurityHeaders } from './modules/security/index.js' export { buildCsp } from './modules/security/index.js' @@ -142,6 +155,8 @@ export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js' export { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js' export type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js' export { + AI_ASSISTANT_BOTS, + AI_TRAINING_BOTS, buildAutoFillMetaHook, buildRobots, buildSitemapEntries, @@ -160,6 +175,8 @@ export { validateFaviconField, } from './modules/seo/index.js' export { buildNoindexField } from './modules/seo/index.js' +export { buildSpeakableJsonLd } from './modules/seo/index.js' +export { buildSummaryField } from './modules/seo/index.js' export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, diff --git a/src/modules/content/blocksToMarkdown.ts b/src/modules/content/blocksToMarkdown.ts new file mode 100644 index 0000000..a8af491 --- /dev/null +++ b/src/modules/content/blocksToMarkdown.ts @@ -0,0 +1,132 @@ +// Import the leaf, not the richtext barrel — the barrel re-exports +// RenderRichText (a React component), which would pull React into this pure, +// server-usable module. +import { lexicalToMarkdown } from '../richtext/lexicalToMarkdown.js' + +/** + * Converts a page's `blocks` layout to Markdown by CONVENTION — the same field + * names the project already standardises on (heading, subheading, body, + * content, image, items/faq/…; see the naming rules in agents.md). The plugin + * can't know each project's block shapes, but it CAN rely on those conventions, + * so most blocks convert with zero per-project wiring. Special blocks get an + * `overrides` entry keyed by blockType. + * + * Output is for AI/agent consumption (per-page Markdown, llms-full.txt), not + * on-page rendering — it extracts readable text, not pixel-perfect layout. + * + * blocksToMarkdown(page.layout) + * blocksToMarkdown(page.layout, { + * overrides: { gallery: (b) => `(${(b.images as unknown[])?.length ?? 0} photos)` }, + * }) + */ + +type Block = Record & { blockType?: string } +type BlockToMarkdown = (block: Block) => string + +type BlocksToMarkdownArgs = { + /** Per-blockType custom renderers. Return '' to omit a block. */ + overrides?: Record +} + +const HEADING_KEYS = new Set(['heading', 'title']) +const SUBHEADING_KEYS = new Set(['subheading', 'subtitle']) +const QUESTION_KEYS = new Set(['question']) +const TEXT_KEYS = new Set([ + 'body', + 'text', + 'description', + 'excerpt', + 'summary', + 'answer', + 'caption', + 'label', + 'content', +]) +const ARRAY_KEYS = new Set([ + 'items', + 'features', + 'faq', + 'faqs', + 'cards', + 'columns', + 'rows', + 'questions', + 'services', + 'steps', + 'points', + 'benefits', + 'list', +]) + +/** A populated richText value is an object with a `root`. */ +function isRichText(v: unknown): boolean { + return !!v && typeof v === 'object' && 'root' in (v as Record) +} + +/** A populated upload (image) is an object with a `url`. */ +function imageMarkdown(v: unknown): string { + if (!v || typeof v !== 'object') return '' + const o = v as Record + const url = typeof o.url === 'string' ? o.url : '' + const alt = typeof o.alt === 'string' ? o.alt : '' + return url ? `![${alt}](${url})` : '' +} + +/** Extract readable Markdown from one block's known content fields. */ +function extractBlock(block: Block, depth: number): string { + const lines: string[] = [] + + for (const [key, value] of Object.entries(block)) { + if (value == null) continue + + if (HEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) { + lines.push(`## ${value.trim()}`) + } else if (SUBHEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) { + lines.push(`### ${value.trim()}`) + } else if (QUESTION_KEYS.has(key) && typeof value === 'string' && value.trim()) { + lines.push(`**${value.trim()}**`) + } else if (key === 'image') { + const img = imageMarkdown(value) + if (img) lines.push(img) + } else if (isRichText(value)) { + const md = lexicalToMarkdown(value as never) + if (md) lines.push(md) + } else if (TEXT_KEYS.has(key) && typeof value === 'string' && value.trim()) { + lines.push(value.trim()) + } else if (ARRAY_KEYS.has(key) && Array.isArray(value) && depth < 4) { + for (const item of value) { + if (item && typeof item === 'object') { + const sub = extractBlock(item as Block, depth + 1) + if (sub.trim()) lines.push(sub) + } else if (typeof item === 'string' && item.trim()) { + lines.push(`- ${item.trim()}`) + } + } + } + } + + return lines.join('\n\n') +} + +export function blocksToMarkdown(layout: unknown, args: BlocksToMarkdownArgs = {}): string { + if (!Array.isArray(layout)) return '' + const { overrides = {} } = args + const out: string[] = [] + + for (const block of layout) { + if (!block || typeof block !== 'object') continue + const b = block as Block + const type = typeof b.blockType === 'string' ? b.blockType : '' + + if (type && overrides[type]) { + const md = overrides[type](b) + if (md.trim()) out.push(md.trim()) + continue + } + + const md = extractBlock(b, 0) + if (md.trim()) out.push(md.trim()) + } + + return out.join('\n\n').trim() +} diff --git a/src/modules/content/createMarkdownRenderer.ts b/src/modules/content/createMarkdownRenderer.ts new file mode 100644 index 0000000..55f762f --- /dev/null +++ b/src/modules/content/createMarkdownRenderer.ts @@ -0,0 +1,123 @@ +import type { BasePayload } from 'payload' + +import type { ContentOption } from './types.js' + +import { blocksToMarkdown } from './blocksToMarkdown.js' +import { resolveRoute } from './resolveRoute.js' + +type CreateMarkdownRendererArgs = { + /** Pages collection. Default 'pages'. */ + collection?: string + /** Archive-backed collections, same value as the plugin option (optional). */ + content?: ContentOption + /** Prepend a YAML frontmatter block (title/description/locale). Default true. */ + frontmatter?: boolean + /** Field holding the block layout. Default 'layout'. */ + layoutField?: string + /** Per-blockType overrides passed to blocksToMarkdown. */ + overrides?: Record) => string> + /** SiteSettings global slug. Default 'site-settings'. */ + settingsSlug?: string +} + +type MarkdownContext = { + locale: string + payload: BasePayload + /** Route slug segments; empty/undefined = locale root (home). */ + slug?: string[] +} + +type DocShape = { + [key: string]: unknown + meta?: { description?: null | string } | null + title?: null | string +} + +function yamlEscape(v: string): string { + return `"${v.replace(/"/g, '\\"')}"` +} + +/** + * Returns a function that renders a page (or archive/entry) to clean Markdown — + * title, meta description, then the block layout via blocksToMarkdown. The + * point is AI-readability: an agent (Claude's WebFetch, GPT, Perplexity) gets + * structured Markdown instead of parsing HTML, so it reads the page reliably. + * + * Mirrors createPageMetadata: the plugin can't call getPayload, so it returns a + * function the project invokes from its route handler. + * + * // app/md/[locale]/[[...slug]]/route.ts (serves /md/pl/o-nas as text/markdown) + * import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit' + * import { getPayload } from 'payload' + * import config from '@payload-config' + * const render = createMarkdownRenderer({ content }) + * export const dynamic = 'force-dynamic' + * export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) { + * const { locale, slug } = await params + * const md = await render({ payload: await getPayload({ config }), locale, slug }) + * return markdownResponse(md) + * } + * + * Returns null when the route doesn't resolve (so the handler can 404). + */ +export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) { + const { + collection = 'pages', + content, + frontmatter = true, + layoutField = 'layout', + overrides, + settingsSlug = 'site-settings', + } = args + + return async function render({ slug, locale, payload }: MarkdownContext): Promise { + const route = await resolveRoute({ + content, + locale, + pagesSlug: collection, + payload, + segments: slug, + settingsSlug, + }) + if (!route) {return null} + + const doc = route.doc as DocShape + const title = typeof doc.title === 'string' ? doc.title : '' + const description = typeof doc.meta?.description === 'string' ? doc.meta.description : '' + const body = blocksToMarkdown(doc[layoutField], { overrides }) + + const parts: string[] = [] + + if (frontmatter) { + const fm = ['---', `locale: ${locale}`] + if (title) {fm.push(`title: ${yamlEscape(title)}`)} + if (description) {fm.push(`description: ${yamlEscape(description)}`)} + fm.push('---') + parts.push(fm.join('\n')) + } + + if (title) {parts.push(`# ${title}`)} + if (description) {parts.push(`_${description}_`)} + if (body) {parts.push(body)} + + const md = parts.join('\n\n').trim() + return md || null + } +} + +/** + * Wraps a Markdown string in a `text/markdown` Response, or a 404 when null. + * Uses the global Response — no next/server import. + */ +export function markdownResponse(md: null | string): Response { + if (md == null) { + return new Response('Not found', { headers: { 'content-type': 'text/plain' }, status: 404 }) + } + return new Response(md, { + headers: { + 'cache-control': 'public, max-age=0, s-maxage=3600, stale-while-revalidate=86400', + 'content-type': 'text/markdown; charset=utf-8', + }, + status: 200, + }) +} diff --git a/src/modules/content/createSearchRoute.ts b/src/modules/content/createSearchRoute.ts new file mode 100644 index 0000000..fcc3fbb --- /dev/null +++ b/src/modules/content/createSearchRoute.ts @@ -0,0 +1,97 @@ +import type { BasePayload } from 'payload' + +import type { I18nConfig } from '../i18n/index.js' + +import { searchContent } from './searchContent.js' + +type CreateSearchRouteArgs = { + /** Absolute origin to prefix result URLs with. */ + baseUrl?: string + /** Pages collection. Default 'pages'. */ + collection?: string + config: I18nConfig + /** Default result cap when ?limit is absent. Default 10. */ + defaultLimit?: number + getCachedPayload: () => Promise + /** Home slug map/string so the home result collapses to root. */ + homeSlug?: Record | string + /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */ + summaryField?: string +} + +/** + * A JSON content-search endpoint. Powers both the site's own search UI and + * external agents — one ranking, one source of truth (shares searchContent with + * the MCP server's search_content tool). + * + * // app/api/search/route.ts + * import { createSearchRoute } from '@intecion/ipal-kit' + * import { getCachedPayload } from '@/lib/content' + * import { i18nConfig } from '@/i18n.config' + * export const dynamic = 'force-dynamic' + * export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig, + * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! }) + * + * Query params: `q` (required), `locale`, `limit`. Response: + * { query, locale, count, results: [{ title, url, description?, slug }] } + * + * Uses the global Request/Response — no next/server import. + */ +export function createSearchRoute( + args: CreateSearchRouteArgs, +): (req: Request) => Promise { + const { + baseUrl, + collection = 'pages', + config, + defaultLimit = 10, + getCachedPayload, + homeSlug, + summaryField, + } = args + + return async (req: Request) => { + const url = new URL(req.url) + const query = url.searchParams.get('q')?.trim() ?? '' + const locale = url.searchParams.get('locale') ?? undefined + const limitParam = url.searchParams.get('limit') + const limit = limitParam ? Number(limitParam) : defaultLimit + + if (!query) { + return Response.json( + { count: 0, error: 'Missing ?q', query: '', results: [] }, + { headers: { 'cache-control': 'no-store' }, status: 400 }, + ) + } + + try { + const payload = await getCachedPayload() + const results = await searchContent({ + baseUrl, + collection, + config, + homeSlug, + limit, + locale, + payload, + query, + summaryField, + }) + return Response.json( + { count: results.length, locale: locale ?? config.defaultLocale, query, results }, + { + headers: { + 'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600', + }, + }, + ) + } catch (err) { + // DB unreachable (build) or unexpected — empty result rather than 500. + console.warn('[ipal] createSearchRoute: search failed:', err) + return Response.json( + { count: 0, query, results: [] }, + { headers: { 'cache-control': 'no-store' }, status: 200 }, + ) + } + } +} diff --git a/src/modules/content/index.ts b/src/modules/content/index.ts index 8fe4d6f..15cf0f4 100644 --- a/src/modules/content/index.ts +++ b/src/modules/content/index.ts @@ -1,9 +1,15 @@ export { buildArchiveFields } from './archiveFields.js' +export { blocksToMarkdown } from './blocksToMarkdown.js' +export { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js' +export { createSearchRoute } from './createSearchRoute.js' export { getArchiveEntries } from './getArchiveEntries.js' export type { ArchiveEntries } from './getArchiveEntries.js' +export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js' export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js' export { resolveRedirect } from './resolveRedirect.js' export { resolveRoute } from './resolveRoute.js' export type { ResolvedRoute } from './resolveRoute.js' +export { searchContent } from './searchContent.js' +export type { SearchResult } from './searchContent.js' export type { ContentCollectionOption, ContentOption } from './types.js' export { archiveFieldName } from './types.js' diff --git a/src/modules/content/markdownNegotiation.ts b/src/modules/content/markdownNegotiation.ts new file mode 100644 index 0000000..232913b --- /dev/null +++ b/src/modules/content/markdownNegotiation.ts @@ -0,0 +1,66 @@ +/** + * Helpers for making the per-page Markdown (createMarkdownRenderer) discoverable + * and negotiable, so AI agents reliably find and read it. + * + * Two mechanisms: + * - `markdownHref` — the `` href a + * page advertises, so an agent fetching the HTML sees there's a Markdown + * version and can switch to it. + * - `prefersMarkdown` — reads the Accept header, so the same URL can serve + * Markdown when asked (content negotiation via a proxy rewrite). + */ + +/** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */ +export const MARKDOWN_PREFIX = '/md' + +/** + * The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so + * the discovery link and the route agree. + * + * markdownHref('/pl/o-nas') // '/md/pl/o-nas' + * markdownHref('/pl/o-nas', '/ai') // '/ai/pl/o-nas' + * + * Advertise it from Next metadata so every page's points to its Markdown: + * + * // generateMetadata + * return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } } + */ +export function markdownHref(pathname: string, prefix: string = MARKDOWN_PREFIX): string { + const clean = pathname.startsWith('/') ? pathname : `/${pathname}` + const p = prefix.replace(/\/$/, '') + return `${p}${clean === '/' ? '' : clean}` || p +} + +/** + * True when the client asked for Markdown via the Accept header (q-values + * respected: a higher-weighted text/html wins). Accepts a header string, a + * Headers object, or a Request. Use it in proxy.ts to serve the same URL as + * Markdown when an agent negotiates for it: + * + * // proxy.ts + * if (prefersMarkdown(request)) { + * return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url)) + * } + */ +export function prefersMarkdown(input: Headers | null | Request | string | undefined): boolean { + let accept: null | string = null + if (!input) {return false} + if (typeof input === 'string') {accept = input} + else if (input instanceof Headers) {accept = input.get('accept')} + else if ('headers' in input && input.headers) {accept = input.headers.get('accept')} + if (!accept) {return false} + + // Parse "type/subtype;q=0.8" entries into {type, q}. + const entries = accept.split(',').map((part) => { + const [type, ...params] = part.trim().split(';') + const qParam = params.find((p) => p.trim().startsWith('q=')) + const q = qParam ? Number(qParam.split('=')[1]) : 1 + return { type: type.trim().toLowerCase(), q: Number.isFinite(q) ? q : 1 } + }) + + const md = entries.find((e) => e.type === 'text/markdown') + if (!md) {return false} + // Markdown must be at least as preferred as html (and html not strictly higher). + const html = entries.find((e) => e.type === 'text/html') + return !html || md.q >= html.q +} diff --git a/src/modules/content/searchContent.ts b/src/modules/content/searchContent.ts new file mode 100644 index 0000000..6f7000e --- /dev/null +++ b/src/modules/content/searchContent.ts @@ -0,0 +1,117 @@ +import type { BasePayload } from 'payload' + +import type { I18nConfig } from '../i18n/index.js' + +import { buildLocalizedPath, getDefaultLocale, isValidLocale } from '../i18n/index.js' + +export type SearchResult = { + description?: string + slug: string + title: string + /** Locale-aware path, prefixed with baseUrl when given. */ + url: string +} + +type SearchContentArgs = { + /** Absolute origin to prefix URLs with. Omit for relative paths. */ + baseUrl?: string + /** Pages collection. Default 'pages'. */ + collection?: string + config: I18nConfig + /** Home slug map/string so the home result collapses to root. */ + homeSlug?: Record | string + /** Max results. Default 10, clamped 1–50. */ + limit?: number + /** Locale to search/return. Defaults to config.defaultLocale; invalid → default. */ + locale?: string + payload: BasePayload + /** Keywords. */ + query: string + /** + * Field holding a richer AI summary (see buildSummaryField). When set and + * present on a doc, it's preferred over meta.description for the result's + * description. + */ + summaryField?: string +} + +type PageRow = { + [key: string]: unknown + _status?: string + id: number | string + meta?: { description?: unknown; noindex?: boolean } | null + slug?: unknown + title?: unknown +} + +/** + * Shared content search: title / meta-description keyword match over a + * collection, returning structured results (published, non-noindex only). One + * implementation behind BOTH the JSON search route (createSearchRoute) and the + * MCP server's search_content tool — so site search, API and AI all rank the + * same way. + * + * Degrades to [] (never throws) when the collection's fields aren't queryable — + * same guard class as the drafts/_status lesson. + */ +export async function searchContent({ + baseUrl, + collection = 'pages', + config, + homeSlug, + limit = 10, + locale, + payload, + query, + summaryField, +}: SearchContentArgs): Promise { + const q = query.trim() + if (!q) {return []} + + const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config) + const max = Math.min(Math.max(Math.trunc(limit) || 10, 1), 50) + const origin = baseUrl?.replace(/\/$/, '') ?? '' + + let docs: PageRow[] = [] + try { + const res = await payload.find({ + collection: collection as never, + depth: 0, + limit: max * 3, // over-fetch; drafts/noindex filtered in memory + locale: loc as never, + where: { + or: [{ title: { like: q } }, { 'meta.description': { like: q } }], + } as never, + }) + docs = (res?.docs ?? []) as PageRow[] + } catch { + return [] + } + + const results: SearchResult[] = [] + for (const doc of docs) { + if (doc._status && doc._status !== 'published') {continue} + if (doc.meta?.noindex) {continue} + const title = typeof doc.title === 'string' ? doc.title : undefined + const slug = typeof doc.slug === 'string' ? doc.slug : undefined + if (!title || !slug) {continue} + const path = buildLocalizedPath({ config, homeSlug, locale: loc, slugs: { [loc]: slug } }) + // Prefer the richer AI summary when configured and present, else meta.description. + const summary = + summaryField && typeof doc[summaryField] === 'string' + ? (doc[summaryField]) + : undefined + const description = + summary?.trim() || + (typeof doc.meta?.description === 'string' ? doc.meta.description : undefined) + results.push({ + slug, + title, + url: `${origin}${path ?? `/${slug}`}`, + ...(description ? { description } : {}), + }) + if (results.length >= max) {break} + } + + return results +} diff --git a/src/modules/mcp/createMcpRoute.ts b/src/modules/mcp/createMcpRoute.ts new file mode 100644 index 0000000..a8ed5a4 --- /dev/null +++ b/src/modules/mcp/createMcpRoute.ts @@ -0,0 +1,232 @@ +import type { BasePayload } from 'payload' + +import type { ContentOption } from '../content/index.js' +import type { I18nConfig } from '../i18n/index.js' + +import { createMarkdownRenderer, searchContent } from '../content/index.js' +import { getDefaultLocale, isValidLocale } from '../i18n/index.js' + +/** + * A read-only MCP (Model Context Protocol) server for the client site, as a Next + * route handler. Lets Claude / any MCP client CONNECT to the site and query it + * directly — search content, fetch a page as Markdown — instead of scraping + * HTML. This is the "better integration" layer on top of the Markdown/llms work. + * + * Dependency-free on purpose: it does NOT pull in @modelcontextprotocol/sdk + * (that would be an imposed dependency, and its API moves). It implements the + * minimal JSON-RPC surface a read-only server needs over the Streamable-HTTP + * transport: initialize, tools/list, tools/call, ping. Uses the global + * Request/Response — no next/server import. + * + * Exposes two tools: + * - search_content({ query, locale?, limit? }) → matching pages (title, url, description) + * - get_page({ path }) → that page as Markdown + * + * // app/api/mcp/route.ts + * import { createMcpRoute } from '@intecion/ipal-kit' + * import { getCachedPayload } from '@/lib/content' + * import { i18nConfig } from '@/i18n.config' + * export const dynamic = 'force-dynamic' + * const mcp = createMcpRoute({ getCachedPayload, config: i18nConfig, + * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, serverName: 'acme-site' }) + * export const POST = mcp.POST + * export const GET = mcp.GET + * + * Add it in Claude as a custom connector pointing at https://site/api/mcp. + */ + +const DEFAULT_PROTOCOL = '2025-06-18' + +type CreateMcpRouteArgs = { + /** Absolute origin for building result URLs. */ + baseUrl?: string + /** Pages collection. Default 'pages'. */ + collection?: string + config: I18nConfig + /** Archive-backed collections (same as the plugin option) for get_page. */ + content?: ContentOption + getCachedPayload: () => Promise + /** Server name advertised in `initialize`. Default 'ipal-site'. */ + serverName?: string + /** Server version advertised in `initialize`. Default '1.0.0'. */ + serverVersion?: string + /** SiteSettings slug. Default 'site-settings'. */ + settingsSlug?: string + /** Field holding a richer AI summary (buildSummaryField) to prefer in search results. */ + summaryField?: string +} + +type JsonRpcId = null | number | string +type JsonRpcRequest = { id?: JsonRpcId; jsonrpc?: string; method?: string; params?: unknown } + +function rpcResult(id: JsonRpcId, result: unknown) { + return { id, jsonrpc: '2.0', result } +} +function rpcError(id: JsonRpcId, code: number, message: string) { + return { id, error: { code, message }, jsonrpc: '2.0' } +} + +function toolText(text: string, isError = false) { + return { content: [{ type: 'text', text }], ...(isError ? { isError: true } : {}) } +} + +export function createMcpRoute(args: CreateMcpRouteArgs) { + const { + baseUrl, + collection = 'pages', + config, + content, + getCachedPayload, + serverName = 'ipal-site', + serverVersion = '1.0.0', + settingsSlug = 'site-settings', + summaryField, + } = args + + const origin = baseUrl?.replace(/\/$/, '') ?? '' + const renderMarkdown = createMarkdownRenderer({ collection, content, settingsSlug }) + + const TOOLS = [ + { + name: 'search_content', + description: + 'Search the site content by keyword. Returns matching pages with title, URL and description.', + inputSchema: { + type: 'object', + properties: { + limit: { type: 'number', description: 'Max results (default 10)' }, + locale: { type: 'string', description: `Locale code (default ${config.defaultLocale})` }, + query: { type: 'string', description: 'Search keywords' }, + }, + required: ['query'], + }, + }, + { + name: 'get_page', + description: + 'Fetch a single page rendered as clean Markdown. `path` is the page path, e.g. /pl/o-nas.', + inputSchema: { + type: 'object', + properties: { + path: { type: 'string', description: 'Page path, e.g. /pl/o-nas or /en/about' }, + }, + required: ['path'], + }, + }, + ] + + async function runSearch(params: Record): Promise { + const query = typeof params.query === 'string' ? params.query.trim() : '' + if (!query) {return 'No query provided.'} + const locale = + typeof params.locale === 'string' && isValidLocale(params.locale, config) + ? params.locale + : getDefaultLocale(config) + const limit = typeof params.limit === 'number' ? params.limit : 10 + + const payload = await getCachedPayload() + // Shared with the JSON search route — one ranking everywhere. + const results = await searchContent({ + baseUrl: origin, + collection, + config, + limit, + locale, + payload, + query, + summaryField, + }) + if (results.length === 0) {return `No pages matched "${query}".`} + return results + .map((r) => `- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`) + .join('\n') + } + + async function getPage(params: Record): Promise { + const raw = typeof params.path === 'string' ? params.path.trim() : '' + if (!raw) {return 'No path provided.'} + const segments = raw + .replace(/^\/+|\/+$/g, '') + .split('/') + .filter(Boolean) + let locale = getDefaultLocale(config) + let slug = segments + if (segments.length && isValidLocale(segments[0], config)) { + locale = segments[0] + slug = segments.slice(1) + } + const payload = await getCachedPayload() + const md = await renderMarkdown({ slug, locale, payload }) + return md ?? `No page found at ${raw}.` + } + + async function handleOne(msg: JsonRpcRequest): Promise { + const { id = null, method, params } = msg + + // Notifications (no id) get no response body. + if (id === null && typeof method === 'string' && method.startsWith('notifications/')) { + return null + } + + switch (method) { + case 'initialize': { + const requested = (params as { protocolVersion?: string } | undefined)?.protocolVersion + return rpcResult(id, { + capabilities: { tools: { listChanged: false } }, + protocolVersion: requested || DEFAULT_PROTOCOL, + serverInfo: { name: serverName, version: serverVersion }, + }) + } + case 'ping': + return rpcResult(id, {}) + case 'tools/call': { + const p = (params ?? {}) as { arguments?: Record; name?: string } + const toolArgs = p.arguments ?? {} + try { + if (p.name === 'search_content') {return rpcResult(id, toolText(await runSearch(toolArgs)))} + if (p.name === 'get_page') {return rpcResult(id, toolText(await getPage(toolArgs)))} + return rpcResult(id, toolText(`Unknown tool: ${p.name}`, true)) + } catch (err) { + return rpcResult(id, toolText(err instanceof Error ? err.message : 'Tool error', true)) + } + } + case 'tools/list': + return rpcResult(id, { tools: TOOLS }) + default: + if (id === null) {return null} // unknown notification + return rpcError(id, -32601, `Method not found: ${method}`) + } + } + + async function POST(req: Request): Promise { + let body: unknown + try { + body = await req.json() + } catch { + return Response.json(rpcError(null, -32700, 'Parse error'), { status: 400 }) + } + + // Batch or single. + if (Array.isArray(body)) { + const out = (await Promise.all(body.map((m) => handleOne(m as JsonRpcRequest)))).filter( + (r): r is object => r !== null, + ) + if (out.length === 0) {return new Response(null, { status: 202 })} + return Response.json(out, { headers: { 'cache-control': 'no-store' } }) + } + + const res = await handleOne(body as JsonRpcRequest) + if (res === null) {return new Response(null, { status: 202 })} + return Response.json(res, { headers: { 'cache-control': 'no-store' } }) + } + + // No server→client SSE stream in this read-only server. + async function GET(): Promise { + return new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', { + headers: { allow: 'POST' }, + status: 405, + }) + } + + return { GET, POST } +} diff --git a/src/modules/mcp/index.ts b/src/modules/mcp/index.ts new file mode 100644 index 0000000..567e107 --- /dev/null +++ b/src/modules/mcp/index.ts @@ -0,0 +1 @@ +export { createMcpRoute } from './createMcpRoute.js' diff --git a/src/modules/richtext/index.ts b/src/modules/richtext/index.ts index 3807783..b727128 100644 --- a/src/modules/richtext/index.ts +++ b/src/modules/richtext/index.ts @@ -1,2 +1,3 @@ +export { lexicalToMarkdown } from './lexicalToMarkdown.js' export { RenderRichText } from './RenderRichText.js' export type { RenderRichTextProps } from './RenderRichText.js' diff --git a/src/modules/richtext/lexicalToMarkdown.ts b/src/modules/richtext/lexicalToMarkdown.ts new file mode 100644 index 0000000..0fa5031 --- /dev/null +++ b/src/modules/richtext/lexicalToMarkdown.ts @@ -0,0 +1,143 @@ +import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical' + +/** + * Converts a Payload Lexical richText value to Markdown — a small, dependency- + * free walker over the serialized node tree. Self-contained on purpose: it does + * NOT rely on a specific `@payloadcms/richtext-lexical` markdown export (those + * move between versions), so a Payload bump can't break it. Covers the node + * types editors actually produce; unknown nodes degrade to their text/children + * rather than throwing. + * + * Used for AI-readable output (per-page Markdown, llms-full.txt) — give an agent + * clean Markdown instead of making it parse HTML. For on-page rendering use + * RenderRichText (the official React converter); this is the text-only sibling. + */ + +type LexNode = { children?: unknown; type?: string } & Record + +// Lexical text format bitflags. +const IS_BOLD = 1 +const IS_ITALIC = 1 << 1 +const IS_STRIKETHROUGH = 1 << 2 +const IS_CODE = 1 << 4 + +function isNodeArray(value: unknown): value is LexNode[] { + return Array.isArray(value) +} + +function wrapText(text: string, format: number): string { + if (!text) {return text} + // Don't wrap pure whitespace — would produce "** **". + if (!text.trim()) {return text} + let out = text + if (format & IS_CODE) {out = `\`${out}\``} + if (format & IS_BOLD) {out = `**${out}**`} + if (format & IS_ITALIC) {out = `_${out}_`} + if (format & IS_STRIKETHROUGH) {out = `~~${out}~~`} + return out +} + +/** Render inline children (text, links, line breaks) to a single string. */ +function inline(nodes: unknown): string { + if (!isNodeArray(nodes)) {return ''} + let out = '' + for (const node of nodes) { + if (!node || typeof node !== 'object') {continue} + const type = node.type + + if (type === 'text') { + const text = typeof node.text === 'string' ? node.text : '' + const format = typeof node.format === 'number' ? node.format : 0 + out += wrapText(text, format) + } else if (type === 'linebreak') { + out += '\n' + } else if (type === 'link') { + const fields = (node.fields ?? {}) as Record + const url = + typeof fields.url === 'string' + ? fields.url + : typeof (fields.doc as Record)?.value === 'string' + ? ((fields.doc as Record).value as string) + : '' + const label = inline(node.children) + out += url ? `[${label}](${url})` : label + } else if (node.children) { + out += inline(node.children) + } else if (typeof node.text === 'string') { + out += node.text + } + } + return out +} + +/** Render a list (ordered/unordered), handling nesting via indentation. */ +function renderList(node: LexNode, depth: number): string { + const ordered = node.listType === 'number' + const items = isNodeArray(node.children) ? node.children : [] + const indent = ' '.repeat(depth) + const lines: string[] = [] + let i = 1 + for (const item of items) { + if (!item || typeof item !== 'object') {continue} + const marker = ordered ? `${i}.` : '-' + // A listitem may contain inline content and/or a nested list. + const kids = isNodeArray(item.children) ? item.children : [] + const nested = kids.filter((k) => k && typeof k === 'object' && k.type === 'list') + const inlineKids = kids.filter((k) => !(k && typeof k === 'object' && k.type === 'list')) + const text = inline(inlineKids) + if (text.trim()) { + lines.push(`${indent}${marker} ${text}`) + i++ + } + for (const n of nested) {lines.push(renderList(n, depth + 1))} + } + return lines.join('\n') +} + +/** Render a block-level node to Markdown. */ +function block(node: LexNode): string { + const type = node.type + + switch (type) { + case 'heading': { + const level = typeof node.tag === 'string' ? Number(node.tag.replace('h', '')) || 2 : 2 + return `${'#'.repeat(Math.min(level, 6))} ${inline(node.children)}` + } + case 'horizontalrule': + return '---' + case 'list': + return renderList(node, 0) + case 'paragraph': { + const text = inline(node.children) + return text.trim() ? text : '' + } + case 'quote': + return inline(node.children) + .split('\n') + .map((l) => `> ${l}`) + .join('\n') + case 'upload': { + const value = (node.value ?? {}) as Record + const url = typeof value.url === 'string' ? value.url : '' + const alt = typeof value.alt === 'string' ? value.alt : '' + return url ? `![${alt}](${url})` : '' + } + default: + // Unknown block-level node: emit its inline content if any. + return node.children ? inline(node.children) : '' + } +} + +export function lexicalToMarkdown(data: null | SerializedEditorState | undefined): string { + const root = (data as unknown as { root?: LexNode } | null | undefined)?.root + if (!root || !isNodeArray(root.children)) {return ''} + + const blocks: string[] = [] + for (const node of root.children) { + if (!node || typeof node !== 'object') {continue} + const md = block(node) + if (md.trim()) {blocks.push(md)} + } + // Blank line between block-level elements — standard Markdown separation. + return blocks.join('\n\n').trim() +} diff --git a/src/modules/seo/buildLlmsTxt.ts b/src/modules/seo/buildLlmsTxt.ts index ec82bbf..42be1a3 100644 --- a/src/modules/seo/buildLlmsTxt.ts +++ b/src/modules/seo/buildLlmsTxt.ts @@ -2,12 +2,22 @@ import type { BasePayload } from 'payload' import type { I18nConfig } from '../i18n/index.js' +import { blocksToMarkdown } from '../content/blocksToMarkdown.js' import { buildLocalizedPath } from '../i18n/index.js' type BuildLlmsTxtArgs = { /** Absolute site URL (https://…). */ baseUrl: string config: I18nConfig + /** + * Full-content mode (llms-full.txt). When true, each page's full body is + * inlined as Markdown (via blocksToMarkdown) under its heading, so an agent + * gets the whole site in one request — the llmstxt.org "llms-full.txt" + * convention. Default false = the compact index (links + descriptions). + */ + full?: boolean + /** Field holding the block layout (full mode only). Default 'layout'. */ + layoutField?: string /** Locale for names/descriptions. Defaults to config.defaultLocale. */ locale?: string /** Pages collection slug. Defaults to 'pages'. */ @@ -15,6 +25,11 @@ type BuildLlmsTxtArgs = { payload: BasePayload /** Site settings global slug. Defaults to 'site-settings'. */ settingsSlug?: string + /** + * Field holding a richer AI summary (buildSummaryField). When set and present, + * it's used as the page description instead of meta.description. + */ + summaryField?: string } type SettingsShape = { @@ -23,6 +38,7 @@ type SettingsShape = { } type PageRow = { + [key: string]: unknown _status?: string id: number | string meta?: { description?: unknown; noindex?: boolean } | null @@ -62,11 +78,24 @@ type PageRow = { export async function buildLlmsTxt({ baseUrl, config, + full = false, + layoutField = 'layout', locale, pagesSlug = 'pages', payload, settingsSlug = 'site-settings', + summaryField, }: BuildLlmsTxtArgs): Promise { + const pickDescription = (raw: PageRow): string | undefined => { + if ( + summaryField && + typeof raw[summaryField] === 'string' && + (raw[summaryField]).trim() + ) { + return (raw[summaryField]).trim() + } + return typeof raw.meta?.description === 'string' ? raw.meta.description : undefined + } const loc = locale ?? config.defaultLocale const origin = baseUrl.replace(/\/$/, '') @@ -84,9 +113,10 @@ export async function buildLlmsTxt({ // "path cannot be queried: _status" (a real bug report). Draft filtering // happens in memory below, which is safe for every collection. Same as // buildSitemapEntries and generateStaticParams. + // Full mode needs depth:1 so block images/relations populate for the Markdown. const result = await payload.find({ collection: pagesSlug as never, - depth: 0, + depth: full ? 1 : 0, limit: 1000, locale: loc as never, }) @@ -96,6 +126,30 @@ export async function buildLlmsTxt({ lines.push(`> ${description}`, '') } + if (full) { + // Full-content: each published page inlined as Markdown under its heading. + const sections: string[] = [] + for (const raw of result.docs as PageRow[]) { + if (raw._status && raw._status !== 'published') {continue} + if (raw.meta?.noindex) {continue} + + const title = typeof raw.title === 'string' ? raw.title : undefined + const slug = typeof raw.slug === 'string' ? raw.slug : undefined + if (!title || !slug) {continue} + + const path = buildLocalizedPath({ config, locale: loc, slugs: { [loc]: slug } }) + const body = blocksToMarkdown(raw[layoutField]) + const desc = pickDescription(raw) + const parts = [`## ${title}`] + if (path) {parts.push(`${origin}${path}`)} + if (desc) {parts.push(`_${desc}_`)} + if (body) {parts.push(body)} + sections.push(parts.join('\n\n')) + } + if (sections.length > 0) {lines.push(sections.join('\n\n---\n\n'), '')} + return lines.join('\n') + } + const pageLinks: string[] = [] for (const raw of result.docs as PageRow[]) { if (raw._status && raw._status !== 'published') {continue} @@ -108,7 +162,8 @@ export async function buildLlmsTxt({ const path = buildLocalizedPath({ config, locale: loc, slugs: { [loc]: slug } }) if (!path) {continue} - const pageDesc = typeof raw.meta?.description === 'string' ? ` — ${raw.meta.description}` : '' + const desc = pickDescription(raw) + const pageDesc = desc ? ` — ${desc}` : '' pageLinks.push(`- [${title}](${origin}${path})${pageDesc}`) } diff --git a/src/modules/seo/buildRobots.ts b/src/modules/seo/buildRobots.ts index ffd3f54..2e92ef1 100644 --- a/src/modules/seo/buildRobots.ts +++ b/src/modules/seo/buildRobots.ts @@ -1,4 +1,52 @@ +type RobotRule = { allow?: string; disallow?: string[]; userAgent: string | string[] } + +/** + * Known AI user agents, split by purpose: + * - assistant/search bots fetch a page to answer a user's question live or to + * power an AI search index — the ones that make "the chat reads your site" + * work, and that most businesses WANT. + * - training crawlers collect pages to train models — some clients prefer to + * opt out of these while keeping assistant/search visibility. + */ +export const AI_ASSISTANT_BOTS = [ + 'ClaudeBot', + 'Claude-Web', + 'Claude-SearchBot', + 'ChatGPT-User', + 'OAI-SearchBot', + 'PerplexityBot', + 'Perplexity-User', +] as const + +export const AI_TRAINING_BOTS = [ + 'GPTBot', + 'Google-Extended', + 'CCBot', + 'anthropic-ai', + 'Applebot-Extended', + 'Bytespider', + 'Meta-ExternalAgent', +] as const + +type AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false + type BuildRobotsArgs = { + /** Override the assistant/search bot list. */ + aiAssistantAgents?: readonly string[] + /** + * How to treat AI crawlers (assistant/search + training). Default 'allow' — + * explicitly welcome them so the site stays visible to Claude, ChatGPT, + * Perplexity etc. and an accidental future '*' tightening doesn't lock them + * out. Options: + * - 'allow' (default): explicit allow for assistant AND training bots. + * - 'block-training': allow assistant/search bots, disallow training crawlers + * — keep AI answers/visibility, opt out of model training. + * - 'disallow': block all known AI bots. + * - false: emit no AI-specific rules (only the '*' rule). + */ + aiBots?: AiBotsPolicy + /** Override the training crawler list. */ + aiTrainingAgents?: readonly string[] /** Absolute origin, e.g. 'https://example.com'. */ baseUrl: string /** Paths to disallow. Defaults to Payload's admin and API. */ @@ -8,17 +56,19 @@ type BuildRobotsArgs = { } /** - * Shape for Next's `app/robots.ts`. + * Shape for Next's `app/robots.ts`. `rules` may be a single rule or an array + * (Next accepts both) — it becomes an array when AI-bot rules are added. */ export type RobotsRules = { host?: string - rules: { allow?: string; disallow?: string[]; userAgent: string } + rules: RobotRule | RobotRule[] sitemap?: string } /** * Builds robots rules that allow crawling everything except the admin panel and - * API, and point crawlers at the sitemap. + * API, point crawlers at the sitemap, and (by default) explicitly welcome AI + * assistant/search/training bots. * * ```ts * // app/robots.ts @@ -29,20 +79,42 @@ export type RobotsRules = { * * The admin and API are disallowed by default — no reason for them in the index, * and it keeps crawl budget on real content. + * + * AI visibility: the #1 reason "the chat won't read the site" is an AI user + * agent being blocked (or not explicitly allowed under a tightened '*' rule). + * `aiBots: 'allow'` (default) emits explicit allow rules for ClaudeBot, GPTBot, + * PerplexityBot, Google-Extended and friends. To keep AI answers but opt out of + * model training, use `aiBots: 'block-training'`. To block them all, 'disallow'. + * + * Pass custom disallow to block parametrized/thin URLs that waste crawl budget: + * ```ts + * buildRobots({ baseUrl, disallow: ['/admin', '/api', '/*?meter=*', '/*?s=*'] }) + * ``` */ export function buildRobots({ + aiAssistantAgents = AI_ASSISTANT_BOTS, + aiBots = 'allow', + aiTrainingAgents = AI_TRAINING_BOTS, baseUrl, disallow = ['/admin', '/api'], sitemap = true, }: BuildRobotsArgs): RobotsRules { const origin = baseUrl.replace(/\/$/, '') + const baseRule: RobotRule = { allow: '/', disallow, userAgent: '*' } + + const aiRules: RobotRule[] = [] + if (aiBots === 'allow') { + aiRules.push({ allow: '/', disallow, userAgent: [...aiAssistantAgents, ...aiTrainingAgents] }) + } else if (aiBots === 'block-training') { + aiRules.push({ allow: '/', disallow, userAgent: [...aiAssistantAgents] }) + aiRules.push({ disallow: ['/'], userAgent: [...aiTrainingAgents] }) + } else if (aiBots === 'disallow') { + aiRules.push({ disallow: ['/'], userAgent: [...aiAssistantAgents, ...aiTrainingAgents] }) + } + return { - rules: { - allow: '/', - disallow, - userAgent: '*', - }, + rules: aiRules.length > 0 ? [baseRule, ...aiRules] : baseRule, ...(sitemap ? { sitemap: `${origin}/sitemap.xml` } : {}), host: origin, } diff --git a/src/modules/seo/buildSpeakableJsonLd.ts b/src/modules/seo/buildSpeakableJsonLd.ts new file mode 100644 index 0000000..c387a50 --- /dev/null +++ b/src/modules/seo/buildSpeakableJsonLd.ts @@ -0,0 +1,45 @@ +type SpeakableJsonLdArgs = { + /** + * CSS selectors marking the parts best suited to be read aloud by voice + * assistants / AI (a summary, the lead paragraph, key answer). Default + * ['h1', '.speakable']. Keep it to genuinely readable, self-contained text — + * not nav or boilerplate. + */ + cssSelectors?: string[] + /** Optional @id to join this node into a @graph (e.g. `${url}#webpage`). */ + id?: string + /** Canonical URL of the page this describes. */ + url: string +} + +/** + * Builds WebPage JSON-LD with a `speakable` SpeakableSpecification — tells voice + * assistants and AI which parts of the page are meant to be read aloud / + * quoted. A GEO signal: pairs with the Markdown/llms work to make the page's key + * content easy for assistants to lift cleanly. + * + * Add to the page's @graph via JsonLdGraph (recommended) or emit standalone: + * + * import { buildSpeakableJsonLd } from '@intecion/ipal-kit' + * const node = buildSpeakableJsonLd({ url: canonical, cssSelectors: ['h1', '.lead'] }) + * + * Mark the matching elements in the project markup (e.g. className="speakable" + * or a `.lead` summary). Selectors that match nothing are simply ignored by + * consumers — but don't point at nav/boilerplate. + */ +export function buildSpeakableJsonLd({ + id, + cssSelectors = ['h1', '.speakable'], + url, +}: SpeakableJsonLdArgs) { + return { + '@context': 'https://schema.org', + '@type': 'WebPage', + ...(id ? { '@id': id } : {}), + speakable: { + '@type': 'SpeakableSpecification', + cssSelector: cssSelectors, + }, + url, + } +} diff --git a/src/modules/seo/buildSummaryField.ts b/src/modules/seo/buildSummaryField.ts new file mode 100644 index 0000000..6cbfd5b --- /dev/null +++ b/src/modules/seo/buildSummaryField.ts @@ -0,0 +1,102 @@ +import type { Field, FieldHook, TextareaField } from 'payload' + +import { blocksToMarkdown } from '../content/blocksToMarkdown.js' + +type BuildSummaryFieldArgs = { + /** Auto-fill from page content when the editor leaves it empty. Default true. */ + autoFill?: boolean + /** Help text under the field. */ + description?: string + /** Sidebar/admin label. */ + label?: string + /** Block layout field to derive the summary from. Default 'layout'. */ + layoutField?: string + /** Target length for the auto-generated summary. Default 300. */ + maxLength?: number + /** Field name. Default 'aiSummary'. */ + name?: string + /** Extend/override the generated textarea (position, access…). */ + overrides?: Partial +} + +/** Rough Markdown → plain text, enough for a summary (drops syntax, keeps words). */ +function mdToPlain(md: string): string { + return md + .replace(/!\[[^\]]*\]\([^)]*\)/g, '') // images + .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // links → their text + .replace(/^#{1,6}\s+/gm, '') // heading markers + .replace(/^[>\-*]\s+/gm, '') // quote/list markers + .replace(/[*_~`]/g, '') // inline emphasis/code marks + .replace(/\s+/g, ' ') + .trim() +} + +/** Truncate at a word boundary, adding an ellipsis when cut. */ +function truncate(text: string, max: number): string { + if (text.length <= max) {return text} + const slice = text.slice(0, max) + const lastSpace = slice.lastIndexOf(' ') + return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…` +} + +/** + * A localized `aiSummary` textarea — a concise, human-written (or auto-derived) + * description of the page, richer than the SEO meta description. It's the + * preferred description for AI-facing surfaces: pass `summaryField: 'aiSummary'` + * to buildLlmsTxt and searchContent and they'll use it over meta.description. + * + * With `autoFill` (default), an empty summary is filled on save from the page's + * own content (blocks → plain text, trimmed to ~maxLength). Editors can always + * overwrite it — auto-fill only runs when the field is blank, never clobbers a + * manual summary. Derived from the page's OWN content, so no hard-coded data. + * + * // collections/Pages.ts + * import { buildSummaryField } from '@intecion/ipal-kit' + * fields: [ /* … *\/ buildSummaryField() ] + * + * // then, richer AI descriptions: + * buildLlmsTxt({ …, summaryField: 'aiSummary' }) + * createSearchRoute({ …, summaryField: 'aiSummary' }) + */ +export function buildSummaryField(args: BuildSummaryFieldArgs = {}): Field { + const { + name = 'aiSummary', + autoFill = true, + description = 'Zwięzły opis strony dla agentów AI i llms.txt (bogatszy niż meta description). Puste → generowane automatycznie z treści.', + label = 'Streszczenie dla AI', + layoutField = 'layout', + maxLength = 300, + overrides = {}, + } = args + + const autofillHook: FieldHook = ({ data, value }) => { + if (typeof value === 'string' && value.trim()) {return value} // never clobber a manual summary + if (!data || typeof data !== 'object') {return value} + const layout = (data as Record)[layoutField] + const md = blocksToMarkdown(layout) + if (!md) {return value} + const plain = mdToPlain(md) + return plain ? truncate(plain, maxLength) : value + } + + const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides + + return { + name, + type: 'textarea', + admin: { + description, + position: 'sidebar', + ...adminOverrides, + }, + hooks: { + ...hooksOverrides, + ...(autoFill + ? { beforeChange: [autofillHook, ...(hooksOverrides?.beforeChange ?? [])] } + : {}), + }, + label, + localized: true, + ...restOverrides, + } as TextareaField +} diff --git a/src/modules/seo/index.ts b/src/modules/seo/index.ts index 2d59909..cdfc103 100644 --- a/src/modules/seo/index.ts +++ b/src/modules/seo/index.ts @@ -11,13 +11,15 @@ export { buildMetadata } from './buildMetadata.js' export type { PageMetadata } from './buildMetadata.js' export { buildNoindexField } from './buildNoindexField.js' export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js' -export { buildRobots } from './buildRobots.js' +export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js' export type { RobotsRules } from './buildRobots.js' export { buildServiceJsonLd } from './buildServiceJsonLd.js' export { buildSitemapEntries } from './buildSitemapEntries.js' export type { SitemapEntry } from './buildSitemapEntries.js' export { buildSitemapXml } from './buildSitemapXml.js' export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js' +export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js' +export { buildSummaryField } from './buildSummaryField.js' export { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js' export { composeTitle } from './composeTitle.js' export type { TitleOrder } from './composeTitle.js' diff --git a/src/modules/seo/routeHandlers.ts b/src/modules/seo/routeHandlers.ts index fa5ffd7..ac205ff 100644 --- a/src/modules/seo/routeHandlers.ts +++ b/src/modules/seo/routeHandlers.ts @@ -18,13 +18,23 @@ import { buildSitemapXml } from './buildSitemapXml.js' * export const dynamic = 'force-dynamic' * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig, * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! }) + * + * For the full-content variant, add a second route with `full: true`: + * + * // app/llms-full.txt/route.ts + * export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig, + * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, full: true }) */ export function createLlmsTxtRoute(opts: { baseUrl: string config: I18nConfig + /** Inline every page's full Markdown (llms-full.txt). Default false. */ + full?: boolean getCachedPayload: () => Promise pagesSlug?: string settingsSlug?: string + /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */ + summaryField?: string }): () => Promise { return async () => { try { @@ -32,9 +42,11 @@ export function createLlmsTxtRoute(opts: { const body = await buildLlmsTxt({ baseUrl: opts.baseUrl, config: opts.config, + full: opts.full, pagesSlug: opts.pagesSlug, payload, settingsSlug: opts.settingsSlug, + summaryField: opts.summaryField, }) return new Response(body, { headers: { 'Content-Type': 'text/plain; charset=utf-8' },