From 786dd346a98031d8716f969d6c32b7cc93ff12b5 Mon Sep 17 00:00:00 2001 From: rasm-its Date: Tue, 13 Oct 2026 15:57:59 +0200 Subject: [PATCH] Fixed notfound headers, r2storage --- dist/modules/frontend/createContentHelpers.js | 5 +- .../frontend/createContentHelpers.js.map | 2 +- dist/modules/pages/LocaleView.d.ts | 21 + dist/modules/pages/LocaleView.js | 23 + dist/modules/pages/LocaleView.js.map | 1 + dist/modules/storage/buildR2Storage.d.ts | 41 +- dist/modules/storage/buildR2Storage.js | 19 +- dist/modules/storage/buildR2Storage.js.map | 2 +- dist/modules/storage/index.d.ts | 1 + dist/modules/storage/index.js.map | 2 +- docs/agent/AGENT.md | 7 +- docs/agent/skills/ipal-audit/scripts/audit.sh | 5 +- docs/agent/skills/ipal-setup/SKILL.md | 2 +- docs/dev/PROGRAMISTA.md | 2 + docs/dev/agent.md | 1223 -------- docs/dev/vibe.md | 2 +- docs/pages.md | 34 +- frontend/[locale]/not-found.tsx | 51 + package.json | 12 +- pnpm-lock.yaml | 2619 ++++++++--------- src/modules/frontend/createContentHelpers.ts | 113 +- src/modules/pages/LocaleView.tsx | 32 + src/modules/storage/buildR2Storage.ts | 51 +- src/modules/storage/index.ts | 1 + 24 files changed, 1506 insertions(+), 2765 deletions(-) create mode 100644 dist/modules/pages/LocaleView.d.ts create mode 100644 dist/modules/pages/LocaleView.js create mode 100644 dist/modules/pages/LocaleView.js.map delete mode 100644 docs/dev/agent.md create mode 100644 frontend/[locale]/not-found.tsx create mode 100644 src/modules/pages/LocaleView.tsx diff --git a/dist/modules/frontend/createContentHelpers.js b/dist/modules/frontend/createContentHelpers.js index 979fa56..3d4acd0 100644 --- a/dist/modules/frontend/createContentHelpers.js +++ b/dist/modules/frontend/createContentHelpers.js @@ -58,8 +58,9 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js'; }); /** * The page assigned as 404 in System Pages (or null → built-in fallback). - * For app/not-found.tsx; never throws. Locale comes from the x-locale header - * set by createProxy (not-found.tsx receives no params). + * For app/not-found.tsx; never throws. not-found.tsx receives no params and + * must NOT read headers() (breaks SSG/ISR) — call this for every configured + * locale and let (client) pick the one from the URL. See pages.md. */ const getNotFoundPage = cache(async (locale)=>{ try { const payload = await getCachedPayload(); diff --git a/dist/modules/frontend/createContentHelpers.js.map b/dist/modules/frontend/createContentHelpers.js.map index ccec158..d7376e6 100644 --- a/dist/modules/frontend/createContentHelpers.js.map +++ b/dist/modules/frontend/createContentHelpers.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/frontend/createContentHelpers.ts"],"sourcesContent":["import type { BasePayload, SanitizedConfig } from 'payload'\n\nimport { getPayload } from 'payload'\nimport { cache } from 'react'\n\nimport type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'\nimport type { I18nConfig } from '../i18n/index.js'\nimport type { RobotsRules, SitemapEntry } from '../seo/index.js'\n\nimport {\n getArchiveEntries,\n resolveNotFoundPage,\n resolveRoute as resolveRouteRaw,\n} from '../content/index.js'\nimport { buildRobots, buildSitemapEntries } from '../seo/index.js'\n\ntype CreateContentHelpersArgs = {\n /**\n * Absolute site origin for sitemap/robots URLs. Falls back to\n * NEXT_PUBLIC_SERVER_URL, then to a relative origin (which most crawlers\n * reject, so set one in production).\n */\n baseUrl?: string\n /**\n * The client's payload config promise (the default export of payload.config).\n * Passed in because the plugin never imports the client's config directly.\n */\n config: Promise | SanitizedConfig\n /** Archive-backed collections, same value as the plugin option. */\n content?: ContentOption\n /**\n * i18n config. Required only if you want the ready-made `sitemap` / `robots`\n * handlers — they need the locale list to emit hreflang.\n */\n i18n?: I18nConfig\n /** Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n}\n\n/**\n * Bundles the per-request data helpers a frontend needs — the same cached\n * wrappers every project was writing by hand (getPayload, settings, locale\n * list, route resolution, archive entries).\n *\n * Everything is wrapped in React `cache()`, so within one request a value is\n * fetched once no matter how many times it's asked for — which matters because\n * Next runs generateMetadata and the page component separately, and both hit\n * these. Crucially the Payload instance is cached *here*, once, so every helper\n * shares it; that's why this is a factory and not loose functions importing a\n * shared module.\n *\n * ```ts\n * // src/lib/content.ts\n * import { createContentHelpers } from 'ipal-kit'\n * import config from '@/payload.config'\n * import { contentConfig } from '@/content.config'\n *\n * export const { getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries } =\n * createContentHelpers({ config, content: contentConfig })\n * ```\n *\n * `resolveRoute` and `getEntries` are separate on purpose: routing decides what\n * a URL is, fetching gets the listing. Metadata generation needs the first and\n * not the second, and a page component composes them in two obvious lines.\n */\nexport function createContentHelpers({\n baseUrl,\n config,\n content,\n i18n,\n pagesSlug = 'pages',\n settingsSlug = 'site-settings',\n}: CreateContentHelpersArgs) {\n const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''\n const getCachedPayload = cache(async (): Promise =>\n getPayload({ config: await config }),\n )\n\n const getConfiguredLocales = cache(async (): Promise => {\n const c = await config\n return c.localization ? c.localization.locales.map((l) => l.code) : []\n })\n\n const getSettings = cache(async (locale: string) => {\n const payload = await getCachedPayload()\n return payload.findGlobal({ slug: settingsSlug as never, depth: 2, locale: locale as never })\n })\n\n /** What does this URL point at? Routing only — no listing data. */\n const resolveRoute = cache(\n async (\n locale: string,\n segments: string[] | undefined,\n page: number,\n ): Promise => {\n const payload = await getCachedPayload()\n return resolveRouteRaw({ content, locale, page, pagesSlug, payload, segments, settingsSlug })\n },\n )\n\n /**\n * The page assigned as 404 in System Pages (or null → built-in fallback).\n * For app/not-found.tsx; never throws. Locale comes from the x-locale header\n * set by createProxy (not-found.tsx receives no params).\n */\n const getNotFoundPage = cache(async (locale: string) => {\n try {\n const payload = await getCachedPayload()\n return await resolveNotFoundPage({ locale, pagesSlug, payload, settingsSlug })\n } catch {\n return null // DB unreachable (container build) — fallback view\n }\n })\n\n /** One page of a collection's entries, for an archive listing. */\n const getEntries = cache(\n async (\n collection: string,\n locale: string,\n page: number,\n perPage: number,\n ): Promise => {\n const payload = await getCachedPayload()\n return getArchiveEntries({ collection, locale, page, payload, perPage })\n },\n )\n\n /**\n * Ready-made handler for Next's `app/sitemap.ts` — every page and entry with\n * per-URL hreflang and lastmod. Re-export it directly:\n *\n * ```ts\n * // app/sitemap.ts\n * export { sitemap as default } from '@/lib/content'\n * export const dynamic = 'force-dynamic' // generate at runtime, not build\n * ```\n *\n * IMPORTANT — container deploys (Coolify/Docker/Railway/CI): Next treats\n * sitemap.ts as STATIC by default and prerenders it during `next build`, which\n * calls into Payload → the database. The build container usually has no access\n * to the internal Docker network, so the DB connection fails (ENOTFOUND) and\n * the build dies. Two defenses:\n * 1. `export const dynamic = 'force-dynamic'` in app/sitemap.ts — skips build\n * prerender, generates at runtime when the DB is reachable (recommended).\n * 2. This handler also catches DB errors and returns [] so that even without\n * (1) the build won't crash — it just ships an empty sitemap until the\n * next runtime regeneration. (1) is still preferred; (2) is a safety net.\n */\n const sitemap = cache(async (): Promise => {\n if (!i18n) {\n throw new Error('[ipal] createContentHelpers: pass `i18n` to use the sitemap handler.')\n }\n try {\n return await buildSitemapEntries({\n baseUrl: origin,\n config: i18n,\n content,\n pagesSlug,\n payload: await getCachedPayload(),\n settingsSlug,\n })\n } catch (error) {\n // DB unreachable (typically a container build with no DB network) — return\n // an empty sitemap instead of failing the build. Runtime regeneration will\n // produce the real one once the DB is reachable. See dynamic='force-dynamic'.\n console.warn(\n '[ipal] sitemap: could not reach the database, returning empty entries ' +\n \"(add `export const dynamic = 'force-dynamic'` to app/sitemap.ts to \" +\n 'generate at runtime and avoid build-time DB access):',\n error,\n )\n return []\n }\n })\n\n /**\n * Ready-made handler for Next's `app/robots.ts`. Re-export directly:\n *\n * ```ts\n * // app/robots.ts\n * export { robots as default } from '@/lib/content'\n * ```\n */\n const robots = (): RobotsRules => buildRobots({ baseUrl: origin })\n\n /**\n * Next.js generateStaticParams for the [[...slug]] route (or\n * [locale]/[[...slug]]). Returns every routable page as a params object, so\n * Next PRE-RENDERS them as static (SSG) instead of dynamic.\n *\n * Why this matters beyond convenience: an optional catch-all with no\n * generateStaticParams is treated as a DYNAMIC route (ƒ), which streams\n * metadata into (crawlers miss it). Providing generateStaticParams\n * compiles routes as SSG (●) — the is synchronous and complete. This is\n * the strongest fix for the metadata-in-head problem (stronger than ISR alone).\n *\n * Handles automatically:\n * - pages collection + content collections (with their archive prefix)\n * - excludes the homepage (maps to { slug: [] } — the root)\n * - excludes drafts and 404/500/system slugs\n * - KEEPS noindex pages (they must still render — noindex controls indexing,\n * not existence; skipping them would force dynamic rendering)\n * - localized slugs (string or per-locale map) both handled\n * - single-locale → { slug }[]; multi-locale → { locale, slug }[]\n *\n * Wire it in the project:\n * // app/(frontend)/[[...slug]]/page.tsx (or [locale]/[[...slug]])\n * export { generateStaticParams } from '@/lib/content'\n */\n const generateStaticParams = async (): Promise<\n Array<{ locale: string; slug: string[] } | { slug: string[] }>\n > => {\n try {\n const payload = await getCachedPayload()\n const locales = i18n ? i18n.locales.map((l) => l.code) : [undefined]\n const singleLocale = !i18n || i18n.locales.length === 1\n\n // Home slug per locale, to exclude the homepage (it's the root, slug []).\n const settings = (await payload\n .findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never })\n .catch(() => null)) as {\n homepage?: { id?: number | string; slug?: unknown }\n notFound?: { id?: number | string } | null\n } | null\n const homeId = settings?.homepage?.id\n // The assigned 404 page renders via not-found.tsx, never as its own URL.\n const notFoundId =\n settings?.notFound?.id !== undefined && settings.notFound.id !== homeId\n ? settings.notFound.id\n : undefined\n\n const EXCLUDED = new Set(['404', '500', 'error', 'not-found'])\n const params: Array<{ locale: string; slug: string[] } | { slug: string[] }> = []\n\n for (const locale of locales) {\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\". We filter drafts in memory below,\n // which is safe for every collection (with or without drafts).\n const result = await payload.find({\n collection: pagesSlug as never,\n depth: 0,\n limit: 1000,\n locale: (locale ?? 'all') as never,\n })\n\n for (const raw of result.docs as Array<{\n _status?: string\n id: number | string\n meta?: { noindex?: boolean } | null\n slug?: unknown\n }>) {\n // Draft filter in memory (safe whether or not the collection has drafts).\n if (raw._status && raw._status !== 'published') {continue}\n if (notFoundId !== undefined && raw.id === notFoundId) {continue}\n\n // NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex\n // page (privacy, cookies, terms) still needs to render — users reach it\n // from the footer and crawlers read its . Pre-render\n // it as SSG so it's fast and its is complete; noindex controls\n // INDEXING, not whether the page exists. Skipping it would force dynamic\n // rendering (the very streaming problem we're avoiding).\n\n if (homeId && raw.id === homeId) {\n // Homepage → root. Emit an empty-slug param so '/' (or '/pl') builds.\n const empty = singleLocale ? { slug: [] } : { slug: [], locale: locale as string }\n if (!params.some((p) => JSON.stringify(p) === JSON.stringify(empty))) {params.push(empty)}\n continue\n }\n\n // Slug may be a plain string OR a localized map ({ pl: 'kontakt' }) when\n // read with locale:'all' or left unflattened. Handle both, or localized\n // pages get silently dropped.\n const rawSlug = raw.slug\n const slug =\n typeof rawSlug === 'string'\n ? rawSlug\n : rawSlug && typeof rawSlug === 'object'\n ? (((rawSlug as Record)[locale ?? ''] as string | undefined) ??\n (Object.values(rawSlug as Record)[0] as string | undefined))\n : undefined\n\n if (!slug || EXCLUDED.has(slug)) {continue}\n\n // Multi-level slugs ('atrakcje/telefon') → array segments.\n const segments = String(slug).split('/').filter(Boolean)\n params.push(\n singleLocale ? { slug: segments } : { slug: segments, locale: locale as string },\n )\n }\n }\n\n return params\n } catch (err) {\n // DB unreachable — typically a container build (Docker/Coolify/CI) with no\n // database network. Return [] so the build doesn't crash: Next falls back\n // to on-demand rendering for the routes, which fill in once the DB is\n // reachable at runtime. Without this every project would need its own\n // try/catch here. (Same graceful-degradation as the sitemap handler.)\n console.warn(\n '[ipal] generateStaticParams: database not reachable during build ' +\n '(Docker/CI) — returning empty params; routes render on-demand at runtime:',\n err,\n )\n return []\n }\n }\n\n return {\n generateStaticParams,\n getCachedPayload,\n getConfiguredLocales,\n getEntries,\n getNotFoundPage,\n getSettings,\n resolveRoute,\n robots,\n sitemap,\n }\n}\n"],"names":["getPayload","cache","getArchiveEntries","resolveNotFoundPage","resolveRoute","resolveRouteRaw","buildRobots","buildSitemapEntries","createContentHelpers","baseUrl","config","content","i18n","pagesSlug","settingsSlug","origin","process","env","NEXT_PUBLIC_SERVER_URL","getCachedPayload","getConfiguredLocales","c","localization","locales","map","l","code","getSettings","locale","payload","findGlobal","slug","depth","segments","page","getNotFoundPage","getEntries","collection","perPage","sitemap","Error","error","console","warn","robots","generateStaticParams","undefined","singleLocale","length","settings","catch","homeId","homepage","id","notFoundId","notFound","EXCLUDED","Set","params","result","find","limit","raw","docs","_status","empty","some","p","JSON","stringify","push","rawSlug","Object","values","has","String","split","filter","Boolean","err"],"mappings":"AAEA,SAASA,UAAU,QAAQ,UAAS;AACpC,SAASC,KAAK,QAAQ,QAAO;AAM7B,SACEC,iBAAiB,EACjBC,mBAAmB,EACnBC,gBAAgBC,eAAe,QAC1B,sBAAqB;AAC5B,SAASC,WAAW,EAAEC,mBAAmB,QAAQ,kBAAiB;AA2BlE;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GACD,OAAO,SAASC,qBAAqB,EACnCC,OAAO,EACPC,MAAM,EACNC,OAAO,EACPC,IAAI,EACJC,YAAY,OAAO,EACnBC,eAAe,eAAe,EACL;IACzB,MAAMC,SAASN,WAAWO,QAAQC,GAAG,CAACC,sBAAsB,IAAI;IAChE,MAAMC,mBAAmBlB,MAAM,UAC7BD,WAAW;YAAEU,QAAQ,MAAMA;QAAO;IAGpC,MAAMU,uBAAuBnB,MAAM;QACjC,MAAMoB,IAAI,MAAMX;QAChB,OAAOW,EAAEC,YAAY,GAAGD,EAAEC,YAAY,CAACC,OAAO,CAACC,GAAG,CAAC,CAACC,IAAMA,EAAEC,IAAI,IAAI,EAAE;IACxE;IAEA,MAAMC,cAAc1B,MAAM,OAAO2B;QAC/B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AC,IAAI;4BAAEA,MAAM,EAAE;4BAAEH,QAAQA;wBAAiB;wBACjF,IAAI,CAAC8B,OAAOQ,IAAI,CAAC,CAACC,IAAMC,KAAKC,SAAS,CAACF,OAAOC,KAAKC,SAAS,CAACJ,SAAS;4BAACP,OAAOY,IAAI,CAACL;wBAAM;wBACzF;oBACF;oBAEA,yEAAyE;oBACzE,wEAAwE;oBACxE,8BAA8B;oBAC9B,MAAMM,UAAUT,IAAI/B,IAAI;oBACxB,MAAMA,OACJ,OAAOwC,YAAY,WACfA,UACAA,WAAW,OAAOA,YAAY,WAC3B,AAAC,AAACA,OAAmC,CAAC3C,UAAU,GAAG,IACnD4C,OAAOC,MAAM,CAACF,QAAmC,CAAC,EAAE,GACrDzB;oBAER,IAAI,CAACf,QAAQyB,SAASkB,GAAG,CAAC3C,OAAO;wBAAC;oBAAQ;oBAE1C,2DAA2D;oBAC3D,MAAME,WAAW0C,OAAO5C,MAAM6C,KAAK,CAAC,KAAKC,MAAM,CAACC;oBAChDpB,OAAOY,IAAI,CACTvB,eAAe;wBAAEhB,MAAME;oBAAS,IAAI;wBAAEF,MAAME;wBAAUL,QAAQA;oBAAiB;gBAEnF;YACF;YAEA,OAAO8B;QACT,EAAE,OAAOqB,KAAK;YACZ,2EAA2E;YAC3E,0EAA0E;YAC1E,sEAAsE;YACtE,sEAAsE;YACtE,sEAAsE;YACtErC,QAAQC,IAAI,CACV,sEACE,6EACFoC;YAEF,OAAO,EAAE;QACX;IACF;IAEA,OAAO;QACLlC;QACA1B;QACAC;QACAgB;QACAD;QACAR;QACAvB;QACAwC;QACAL;IACF;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/frontend/createContentHelpers.ts"],"sourcesContent":["import type { BasePayload, SanitizedConfig } from 'payload'\n\nimport { getPayload } from 'payload'\nimport { cache } from 'react'\n\nimport type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'\nimport type { I18nConfig } from '../i18n/index.js'\nimport type { RobotsRules, SitemapEntry } from '../seo/index.js'\n\nimport {\n getArchiveEntries,\n resolveNotFoundPage,\n resolveRoute as resolveRouteRaw,\n} from '../content/index.js'\nimport { buildRobots, buildSitemapEntries } from '../seo/index.js'\n\ntype CreateContentHelpersArgs = {\n /**\n * Absolute site origin for sitemap/robots URLs. Falls back to\n * NEXT_PUBLIC_SERVER_URL, then to a relative origin (which most crawlers\n * reject, so set one in production).\n */\n baseUrl?: string\n /**\n * The client's payload config promise (the default export of payload.config).\n * Passed in because the plugin never imports the client's config directly.\n */\n config: Promise | SanitizedConfig\n /** Archive-backed collections, same value as the plugin option. */\n content?: ContentOption\n /**\n * i18n config. Required only if you want the ready-made `sitemap` / `robots`\n * handlers — they need the locale list to emit hreflang.\n */\n i18n?: I18nConfig\n /** Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n}\n\n/**\n * Bundles the per-request data helpers a frontend needs — the same cached\n * wrappers every project was writing by hand (getPayload, settings, locale\n * list, route resolution, archive entries).\n *\n * Everything is wrapped in React `cache()`, so within one request a value is\n * fetched once no matter how many times it's asked for — which matters because\n * Next runs generateMetadata and the page component separately, and both hit\n * these. Crucially the Payload instance is cached *here*, once, so every helper\n * shares it; that's why this is a factory and not loose functions importing a\n * shared module.\n *\n * ```ts\n * // src/lib/content.ts\n * import { createContentHelpers } from 'ipal-kit'\n * import config from '@/payload.config'\n * import { contentConfig } from '@/content.config'\n *\n * export const { getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries } =\n * createContentHelpers({ config, content: contentConfig })\n * ```\n *\n * `resolveRoute` and `getEntries` are separate on purpose: routing decides what\n * a URL is, fetching gets the listing. Metadata generation needs the first and\n * not the second, and a page component composes them in two obvious lines.\n */\nexport function createContentHelpers({\n baseUrl,\n config,\n content,\n i18n,\n pagesSlug = 'pages',\n settingsSlug = 'site-settings',\n}: CreateContentHelpersArgs) {\n const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''\n const getCachedPayload = cache(\n async (): Promise => getPayload({ config: await config }),\n )\n\n const getConfiguredLocales = cache(async (): Promise => {\n const c = await config\n return c.localization ? c.localization.locales.map((l) => l.code) : []\n })\n\n const getSettings = cache(async (locale: string) => {\n const payload = await getCachedPayload()\n return payload.findGlobal({ slug: settingsSlug as never, depth: 2, locale: locale as never })\n })\n\n /** What does this URL point at? Routing only — no listing data. */\n const resolveRoute = cache(\n async (\n locale: string,\n segments: string[] | undefined,\n page: number,\n ): Promise => {\n const payload = await getCachedPayload()\n return resolveRouteRaw({ content, locale, page, pagesSlug, payload, segments, settingsSlug })\n },\n )\n\n /**\n * The page assigned as 404 in System Pages (or null → built-in fallback).\n * For app/not-found.tsx; never throws. not-found.tsx receives no params and\n * must NOT read headers() (breaks SSG/ISR) — call this for every configured\n * locale and let (client) pick the one from the URL. See pages.md.\n */\n const getNotFoundPage = cache(async (locale: string) => {\n try {\n const payload = await getCachedPayload()\n return await resolveNotFoundPage({ locale, pagesSlug, payload, settingsSlug })\n } catch {\n return null // DB unreachable (container build) — fallback view\n }\n })\n\n /** One page of a collection's entries, for an archive listing. */\n const getEntries = cache(\n async (\n collection: string,\n locale: string,\n page: number,\n perPage: number,\n ): Promise => {\n const payload = await getCachedPayload()\n return getArchiveEntries({ collection, locale, page, payload, perPage })\n },\n )\n\n /**\n * Ready-made handler for Next's `app/sitemap.ts` — every page and entry with\n * per-URL hreflang and lastmod. Re-export it directly:\n *\n * ```ts\n * // app/sitemap.ts\n * export { sitemap as default } from '@/lib/content'\n * export const dynamic = 'force-dynamic' // generate at runtime, not build\n * ```\n *\n * IMPORTANT — container deploys (Coolify/Docker/Railway/CI): Next treats\n * sitemap.ts as STATIC by default and prerenders it during `next build`, which\n * calls into Payload → the database. The build container usually has no access\n * to the internal Docker network, so the DB connection fails (ENOTFOUND) and\n * the build dies. Two defenses:\n * 1. `export const dynamic = 'force-dynamic'` in app/sitemap.ts — skips build\n * prerender, generates at runtime when the DB is reachable (recommended).\n * 2. This handler also catches DB errors and returns [] so that even without\n * (1) the build won't crash — it just ships an empty sitemap until the\n * next runtime regeneration. (1) is still preferred; (2) is a safety net.\n */\n const sitemap = cache(async (): Promise => {\n if (!i18n) {\n throw new Error(\n '[ipal] createContentHelpers: pass `i18n` to use the sitemap handler.',\n )\n }\n try {\n return await buildSitemapEntries({\n baseUrl: origin,\n config: i18n,\n content,\n pagesSlug,\n payload: await getCachedPayload(),\n settingsSlug,\n })\n } catch (error) {\n // DB unreachable (typically a container build with no DB network) — return\n // an empty sitemap instead of failing the build. Runtime regeneration will\n // produce the real one once the DB is reachable. See dynamic='force-dynamic'.\n console.warn(\n '[ipal] sitemap: could not reach the database, returning empty entries ' +\n \"(add `export const dynamic = 'force-dynamic'` to app/sitemap.ts to \" +\n 'generate at runtime and avoid build-time DB access):',\n error,\n )\n return []\n }\n })\n\n /**\n * Ready-made handler for Next's `app/robots.ts`. Re-export directly:\n *\n * ```ts\n * // app/robots.ts\n * export { robots as default } from '@/lib/content'\n * ```\n */\n const robots = (): RobotsRules => buildRobots({ baseUrl: origin })\n\n /**\n * Next.js generateStaticParams for the [[...slug]] route (or\n * [locale]/[[...slug]]). Returns every routable page as a params object, so\n * Next PRE-RENDERS them as static (SSG) instead of dynamic.\n *\n * Why this matters beyond convenience: an optional catch-all with no\n * generateStaticParams is treated as a DYNAMIC route (ƒ), which streams\n * metadata into (crawlers miss it). Providing generateStaticParams\n * compiles routes as SSG (●) — the is synchronous and complete. This is\n * the strongest fix for the metadata-in-head problem (stronger than ISR alone).\n *\n * Handles automatically:\n * - pages collection + content collections (with their archive prefix)\n * - excludes the homepage (maps to { slug: [] } — the root)\n * - excludes drafts and 404/500/system slugs\n * - KEEPS noindex pages (they must still render — noindex controls indexing,\n * not existence; skipping them would force dynamic rendering)\n * - localized slugs (string or per-locale map) both handled\n * - single-locale → { slug }[]; multi-locale → { locale, slug }[]\n *\n * Wire it in the project:\n * // app/(frontend)/[[...slug]]/page.tsx (or [locale]/[[...slug]])\n * export { generateStaticParams } from '@/lib/content'\n */\n const generateStaticParams = async (): Promise<\n Array<{ locale: string; slug: string[] } | { slug: string[] }>\n > => {\n try {\n const payload = await getCachedPayload()\n const locales = i18n ? i18n.locales.map((l) => l.code) : [undefined]\n const singleLocale = !i18n || i18n.locales.length === 1\n\n // Home slug per locale, to exclude the homepage (it's the root, slug []).\n const settings = (await payload\n .findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never })\n .catch(() => null)) as {\n homepage?: { id?: number | string; slug?: unknown }\n notFound?: { id?: number | string } | null\n } | null\n const homeId = settings?.homepage?.id\n // The assigned 404 page renders via not-found.tsx, never as its own URL.\n const notFoundId =\n settings?.notFound?.id !== undefined && settings.notFound.id !== homeId\n ? settings.notFound.id\n : undefined\n\n const EXCLUDED = new Set(['404', '500', 'error', 'not-found'])\n const params: Array<{ locale: string; slug: string[] } | { slug: string[] }> = []\n\n for (const locale of locales) {\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\". We filter drafts in memory below,\n // which is safe for every collection (with or without drafts).\n const result = await payload.find({\n collection: pagesSlug as never,\n depth: 0,\n limit: 1000,\n locale: (locale ?? 'all') as never,\n })\n\n for (const raw of result.docs as Array<{\n _status?: string\n id: number | string\n meta?: { noindex?: boolean } | null\n slug?: unknown\n }>) {\n // Draft filter in memory (safe whether or not the collection has drafts).\n if (raw._status && raw._status !== 'published') {continue}\n if (notFoundId !== undefined && raw.id === notFoundId) {continue}\n\n // NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex\n // page (privacy, cookies, terms) still needs to render — users reach it\n // from the footer and crawlers read its . Pre-render\n // it as SSG so it's fast and its is complete; noindex controls\n // INDEXING, not whether the page exists. Skipping it would force dynamic\n // rendering (the very streaming problem we're avoiding).\n\n if (homeId && raw.id === homeId) {\n // Homepage → root. Emit an empty-slug param so '/' (or '/pl') builds.\n const empty = singleLocale ? { slug: [] } : { slug: [], locale: locale as string }\n if (!params.some((p) => JSON.stringify(p) === JSON.stringify(empty))) {params.push(empty)}\n continue\n }\n\n // Slug may be a plain string OR a localized map ({ pl: 'kontakt' }) when\n // read with locale:'all' or left unflattened. Handle both, or localized\n // pages get silently dropped.\n const rawSlug = raw.slug\n const slug =\n typeof rawSlug === 'string'\n ? rawSlug\n : rawSlug && typeof rawSlug === 'object'\n ? ((rawSlug as Record)[locale ?? ''] as string | undefined) ??\n (Object.values(rawSlug as Record)[0] as string | undefined)\n : undefined\n\n if (!slug || EXCLUDED.has(slug)) {continue}\n\n // Multi-level slugs ('atrakcje/telefon') → array segments.\n const segments = String(slug).split('/').filter(Boolean)\n params.push(singleLocale ? { slug: segments } : { slug: segments, locale: locale as string })\n }\n }\n\n return params\n } catch (err) {\n // DB unreachable — typically a container build (Docker/Coolify/CI) with no\n // database network. Return [] so the build doesn't crash: Next falls back\n // to on-demand rendering for the routes, which fill in once the DB is\n // reachable at runtime. Without this every project would need its own\n // try/catch here. (Same graceful-degradation as the sitemap handler.)\n console.warn(\n '[ipal] generateStaticParams: database not reachable during build ' +\n '(Docker/CI) — returning empty params; routes render on-demand at runtime:',\n err,\n )\n return []\n }\n }\n\n return {\n generateStaticParams,\n getCachedPayload,\n getConfiguredLocales,\n getEntries,\n getNotFoundPage,\n getSettings,\n resolveRoute,\n robots,\n sitemap,\n }\n}\n"],"names":["getPayload","cache","getArchiveEntries","resolveNotFoundPage","resolveRoute","resolveRouteRaw","buildRobots","buildSitemapEntries","createContentHelpers","baseUrl","config","content","i18n","pagesSlug","settingsSlug","origin","process","env","NEXT_PUBLIC_SERVER_URL","getCachedPayload","getConfiguredLocales","c","localization","locales","map","l","code","getSettings","locale","payload","findGlobal","slug","depth","segments","page","getNotFoundPage","getEntries","collection","perPage","sitemap","Error","error","console","warn","robots","generateStaticParams","undefined","singleLocale","length","settings","catch","homeId","homepage","id","notFoundId","notFound","EXCLUDED","Set","params","result","find","limit","raw","docs","_status","empty","some","p","JSON","stringify","push","raw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,SAASkB,GAAG,CAAC3C,OAAO;wBAAC;oBAAQ;oBAE1C,2DAA2D;oBAC3D,MAAME,WAAW0C,OAAO5C,MAAM6C,KAAK,CAAC,KAAKC,MAAM,CAACC;oBAChDpB,OAAOY,IAAI,CAACvB,eAAe;wBAAEhB,MAAME;oBAAS,IAAI;wBAAEF,MAAME;wBAAUL,QAAQA;oBAAiB;gBAC7F;YACF;YAEE,OAAO8B;QACT,EAAE,OAAOqB,KAAK;YACZ,2EAA2E;YAC3E,0EAA0E;YAC1E,sEAAsE;YACtE,sEAAsE;YACtE,sEAAsE;YACtErC,QAAQC,IAAI,CACV,sEACE,6EACFoC;YAEF,OAAO,EAAE;QACX;IACF;IAEA,OAAO;QACLlC;QACA1B;QACAC;QACAgB;QACAD;QACAR;QACAvB;QACAwC;QACAL;IACF;AACF"} \ No newline at end of file diff --git a/dist/modules/pages/LocaleView.d.ts b/dist/modules/pages/LocaleView.d.ts new file mode 100644 index 0000000..857b4cb --- /dev/null +++ b/dist/modules/pages/LocaleView.d.ts @@ -0,0 +1,21 @@ +import type { ReactNode } from 'react'; +type LocaleViewProps = { + /** Used when the URL has no locale segment (single-locale site) or an unknown one. */ + defaultLocale: string; + /** + * One pre-rendered view per locale, e.g. { pl: , en: … }. + * Rendered on the SERVER (RSC) and passed in as props — this component only + * picks one, so the content can come from the panel and the route stays static. + */ + views: Record; +}; +/** + * Shows the view matching the locale in the current URL (`/en/...` → `en`). + * + * Made for `not-found.tsx`, which receives no `params`: reading the locale with + * `headers()` there turns an SSG/ISR route dynamic ("Page changed from static + * to dynamic at runtime"). `usePathname()` is client-side and static-safe, and + * it also runs during SSR, so the HTML already contains the right language. + */ +export declare function LocaleView({ defaultLocale, views }: LocaleViewProps): import("react/jsx-runtime").JSX.Element; +export {}; diff --git a/dist/modules/pages/LocaleView.js b/dist/modules/pages/LocaleView.js new file mode 100644 index 0000000..1aa9029 --- /dev/null +++ b/dist/modules/pages/LocaleView.js @@ -0,0 +1,23 @@ +'use client'; +import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime"; +// '.js' is required: `next` has no package.json "exports", so NodeNext resolution +// (this plugin's tsconfig) can't find 'next/navigation' without the extension. +// Bundlers in the project resolve the same file either way. +import { usePathname } from 'next/navigation.js'; +/** + * Shows the view matching the locale in the current URL (`/en/...` → `en`). + * + * Made for `not-found.tsx`, which receives no `params`: reading the locale with + * `headers()` there turns an SSG/ISR route dynamic ("Page changed from static + * to dynamic at runtime"). `usePathname()` is client-side and static-safe, and + * it also runs during SSR, so the HTML already contains the right language. + */ export function LocaleView({ defaultLocale, views }) { + const pathname = usePathname() ?? ''; + const segment = pathname.split('/').filter(Boolean)[0] ?? ''; + const locale = segment in views ? segment : defaultLocale; + return /*#__PURE__*/ _jsx(_Fragment, { + children: views[locale] ?? views[defaultLocale] ?? null + }); +} + +//# sourceMappingURL=LocaleView.js.map \ No newline at end of file diff --git a/dist/modules/pages/LocaleView.js.map b/dist/modules/pages/LocaleView.js.map new file mode 100644 index 0000000..afca110 --- /dev/null +++ b/dist/modules/pages/LocaleView.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/pages/LocaleView.tsx"],"sourcesContent":["'use client'\nimport type { ReactNode } from 'react'\n// '.js' is required: `next` has no package.json \"exports\", so NodeNext resolution\n// (this plugin's tsconfig) can't find 'next/navigation' without the extension.\n// Bundlers in the project resolve the same file either way.\nimport { usePathname } from 'next/navigation.js'\n\ntype LocaleViewProps = {\n /** Used when the URL has no locale segment (single-locale site) or an unknown one. */\n defaultLocale: string\n /**\n * One pre-rendered view per locale, e.g. { pl: , en: … }.\n * Rendered on the SERVER (RSC) and passed in as props — this component only\n * picks one, so the content can come from the panel and the route stays static.\n */\n views: Record\n}\n\n/**\n * Shows the view matching the locale in the current URL (`/en/...` → `en`).\n *\n * Made for `not-found.tsx`, which receives no `params`: reading the locale with\n * `headers()` there turns an SSG/ISR route dynamic (\"Page changed from static\n * to dynamic at runtime\"). `usePathname()` is client-side and static-safe, and\n * it also runs during SSR, so the HTML already contains the right language.\n */\nexport function LocaleView({ defaultLocale, views }: LocaleViewProps) {\n const pathname = usePathname() ?? ''\n const segment = pathname.split('/').filter(Boolean)[0] ?? ''\n const locale = segment in views ? segment : defaultLocale\n return <>{views[locale] ?? views[defaultLocale] ?? null}\n}\n"],"names":["usePathname","LocaleView","defaultLocale","views","pathname","segment","split","filter","Boolean","locale"],"mappings":"AAAA;;AAEA,kFAAkF;AAClF,+EAA+E;AAC/E,4DAA4D;AAC5D,SAASA,WAAW,QAAQ,qBAAoB;AAahD;;;;;;;CAOC,GACD,OAAO,SAASC,WAAW,EAAEC,aAAa,EAAEC,KAAK,EAAmB;IAClE,MAAMC,WAAWJ,iBAAiB;IAClC,MAAMK,UAAUD,SAASE,KAAK,CAAC,KAAKC,MAAM,CAACC,QAAQ,CAAC,EAAE,IAAI;IAC1D,MAAMC,SAASJ,WAAWF,QAAQE,UAAUH;IAC5C,qBAAO;kBAAGC,KAAK,CAACM,OAAO,IAAIN,KAAK,CAACD,cAAc,IAAI;;AACrD"} \ No newline at end of file diff --git a/dist/modules/storage/buildR2Storage.d.ts b/dist/modules/storage/buildR2Storage.d.ts index 85f3812..b59257a 100644 --- a/dist/modules/storage/buildR2Storage.d.ts +++ b/dist/modules/storage/buildR2Storage.d.ts @@ -1,4 +1,32 @@ import type { Plugin } from 'payload'; +type GenerateFileURL = (args: { + filename: string; + prefix?: string; +}) => string; +/** + * Minimal shape of `s3Storage` from @payloadcms/storage-s3 — the plugin never + * imports that package (it's optional: projects on local disk don't install it). + * The project injects the real function; TypeScript checks it fits this shape. + */ +export type S3StorageFactory = (options: { + bucket: string; + collections: Record; + config: { + credentials: { + accessKeyId: string; + secretAccessKey: string; + }; + endpoint: string; + forcePathStyle: boolean; + region: string; + }; +}) => Plugin; +export type BuildR2StorageDeps = { + /** `import { s3Storage } from '@payloadcms/storage-s3'` — required when R2 env is set. */ + s3Storage?: S3StorageFactory; +}; /** * Cloudflare R2 media storage — configured from environment variables (agency * infrastructure, not per-project panel data). R2 is S3-compatible, so we use @@ -13,6 +41,17 @@ import type { Plugin } from 'payload'; * storage (useful in dev without R2). This mirrors how mailAdapter degrades * gracefully when a transport isn't configured. * + * The S3 adapter is INJECTED by the project (same pattern as 2FA / NextResponse): + * + * import { s3Storage } from '@payloadcms/storage-s3' + * plugins: [buildR2Storage(['media'], { s3Storage })] + * + * A static import here would make @payloadcms/storage-s3 mandatory for every + * project — including ones on local disk — because this module is exported + * from the package's main entry. + * * @param collections - slugs of upload collections to offload to R2 (e.g. ['media']) + * @param deps - `{ s3Storage }` from @payloadcms/storage-s3 (needed only when R2 env is set) */ -export declare const buildR2Storage: (collections?: string[]) => Plugin; +export declare const buildR2Storage: (collections?: string[], deps?: BuildR2StorageDeps) => Plugin; +export {}; diff --git a/dist/modules/storage/buildR2Storage.js b/dist/modules/storage/buildR2Storage.js index edf45fb..86f9630 100644 --- a/dist/modules/storage/buildR2Storage.js +++ b/dist/modules/storage/buildR2Storage.js @@ -1,4 +1,3 @@ -import { s3Storage } from '@payloadcms/storage-s3'; /** * Cloudflare R2 media storage — configured from environment variables (agency * infrastructure, not per-project panel data). R2 is S3-compatible, so we use @@ -13,10 +12,20 @@ import { s3Storage } from '@payloadcms/storage-s3'; * storage (useful in dev without R2). This mirrors how mailAdapter degrades * gracefully when a transport isn't configured. * + * The S3 adapter is INJECTED by the project (same pattern as 2FA / NextResponse): + * + * import { s3Storage } from '@payloadcms/storage-s3' + * plugins: [buildR2Storage(['media'], { s3Storage })] + * + * A static import here would make @payloadcms/storage-s3 mandatory for every + * project — including ones on local disk — because this module is exported + * from the package's main entry. + * * @param collections - slugs of upload collections to offload to R2 (e.g. ['media']) + * @param deps - `{ s3Storage }` from @payloadcms/storage-s3 (needed only when R2 env is set) */ export const buildR2Storage = (collections = [ 'media' -])=>{ +], deps = {})=>{ const bucket = process.env.R2_BUCKET; const endpoint = process.env.R2_ENDPOINT; const accessKeyId = process.env.R2_ACCESS_KEY_ID; @@ -47,6 +56,12 @@ import { s3Storage } from '@payloadcms/storage-s3'; prefix, filename ].filter(Boolean).join('/') : undefined; + // R2 env is complete → the adapter is required. Fail loudly at boot rather + // than silently storing media on the container disk (lost on redeploy). + const { s3Storage } = deps; + if (!s3Storage) { + throw new Error('[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' + "Install @payloadcms/storage-s3 and pass it: buildR2Storage(['media'], { s3Storage }) " + "with `import { s3Storage } from '@payloadcms/storage-s3'`. See docs/storage.md."); + } const collectionsConfig = {}; for (const slug of collections){ collectionsConfig[slug] = generateFileURL ? { diff --git a/dist/modules/storage/buildR2Storage.js.map b/dist/modules/storage/buildR2Storage.js.map index 70f5679..192145a 100644 --- a/dist/modules/storage/buildR2Storage.js.map +++ b/dist/modules/storage/buildR2Storage.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/storage/buildR2Storage.ts"],"sourcesContent":["import type { Plugin } from 'payload'\n\nimport { s3Storage } from '@payloadcms/storage-s3'\n\n/**\n * Cloudflare R2 media storage — configured from environment variables (agency\n * infrastructure, not per-project panel data). R2 is S3-compatible, so we use\n * @payloadcms/storage-s3 pointed at the R2 endpoint.\n *\n * Storage is infrastructure (like the database or PAYLOAD_SECRET): it binds at\n * boot, and its credentials are agency-owned — so it lives in .env, not the\n * panel. See docs/storage.md for the required variables.\n *\n * Returns the storage plugin when all R2 vars are present; otherwise returns a\n * no-op passthrough so the project falls back to Payload's default local disk\n * storage (useful in dev without R2). This mirrors how mailAdapter degrades\n * gracefully when a transport isn't configured.\n *\n * @param collections - slugs of upload collections to offload to R2 (e.g. ['media'])\n */\nexport const buildR2Storage = (collections: string[] = ['media']): Plugin => {\n const bucket = process.env.R2_BUCKET\n const endpoint = process.env.R2_ENDPOINT\n const accessKeyId = process.env.R2_ACCESS_KEY_ID\n const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY\n\n // Any missing → skip R2, fall back to local disk. Warn so it's not silent.\n if (!bucket || !endpoint || !accessKeyId || !secretAccessKey) {\n return (config) => {\n // Only warn when SOME vars are set (partial config = likely a mistake).\n if (bucket || endpoint || accessKeyId || secretAccessKey) {\n console.warn(\n '[ipal] R2 storage: incomplete env (need R2_BUCKET, R2_ENDPOINT, ' +\n 'R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY). Falling back to local disk.',\n )\n }\n return config\n }\n }\n\n // Public URL for served media. R2 is private by default; its S3 endpoint only\n // accepts uploads and won't serve files (403). With a custom domain\n // (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs\n // pointing there. Without it, uploads work but images don't display publicly.\n // See docs/storage.md.\n const publicUrl = process.env.R2_PUBLIC_URL?.replace(/\\/$/, '') // strip trailing slash\n\n // generateFileURL is a PER-COLLECTION option in @payloadcms/storage-s3 (not a\n // top-level one) — R2 needs it to point served URLs at the custom domain\n // instead of the private S3 endpoint. Each collection gets either `true`\n // (plain offload) or an object carrying generateFileURL when a public URL is set.\n const generateFileURL = publicUrl\n ? ({ filename, prefix }: { filename: string; prefix?: string }) =>\n [publicUrl, prefix, filename].filter(Boolean).join('/')\n : undefined\n\n const collectionsConfig: Record = {}\n for (const slug of collections) {\n collectionsConfig[slug] = generateFileURL ? { generateFileURL } : true\n }\n\n return s3Storage({\n bucket,\n collections: collectionsConfig,\n config: {\n credentials: { accessKeyId, secretAccessKey },\n endpoint,\n region: 'auto', // R2 uses 'auto'\n // R2 requires path-style addressing for S3 compatibility.\n forcePathStyle: true,\n },\n })\n}\n"],"names":["s3Storage","buildR2Storage","collections","bucket","process","env","R2_BUCKET","endpoint","R2_ENDPOINT","accessKeyId","R2_ACCESS_KEY_ID","secretAccessKey","R2_SECRET_ACCESS_KEY","config","console","warn","publicUrl","R2_PUBLIC_URL","replace","generateFileURL","filename","prefix","filter","Boolean","join","undefined","collectionsConfig","slug","credentials","region","forcePathStyle"],"mappings":"AAEA,SAASA,SAAS,QAAQ,yBAAwB;AAElD;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,iBAAiB,CAACC,cAAwB;IAAC;CAAQ;IAC9D,MAAMC,SAASC,QAAQC,GAAG,CAACC,SAAS;IACpC,MAAMC,WAAWH,QAAQC,GAAG,CAACG,WAAW;IACxC,MAAMC,cAAcL,QAAQC,GAAG,CAACK,gBAAgB;IAChD,MAAMC,kBAAkBP,QAAQC,GAAG,CAACO,oBAAoB;IAExD,2EAA2E;IAC3E,IAAI,CAACT,UAAU,CAACI,YAAY,CAACE,eAAe,CAACE,iBAAiB;QAC5D,OAAO,CAACE;YACN,wEAAwE;YACxE,IAAIV,UAAUI,YAAYE,eAAeE,iBAAiB;gBACxDG,QAAQC,IAAI,CACV,qEACE;YAEN;YACA,OAAOF;QACT;IACF;IAEA,8EAA8E;IAC9E,oEAAoE;IACpE,yEAAyE;IACzE,8EAA8E;IAC9E,uBAAuB;IACvB,MAAMG,YAAYZ,QAAQC,GAAG,CAACY,aAAa,EAAEC,QAAQ,OAAO,IAAI,uBAAuB;;IAEvF,8EAA8E;IAC9E,yEAAyE;IACzE,yEAAyE;IACzE,kFAAkF;IAClF,MAAMC,kBAAkBH,YACpB,CAAC,EAAEI,QAAQ,EAAEC,MAAM,EAAyC,GAC1D;YAACL;YAAWK;YAAQD;SAAS,CAACE,MAAM,CAACC,SAASC,IAAI,CAAC,OACrDC;IAEJ,MAAMC,oBAAwF,CAAC;IAC/F,KAAK,MAAMC,QAAQzB,YAAa;QAC9BwB,iBAAiB,CAACC,KAAK,GAAGR,kBAAkB;YAAEA;QAAgB,IAAI;IACpE;IAEA,OAAOnB,UAAU;QACfG;QACAD,aAAawB;QACbb,QAAQ;YACNe,aAAa;gBAAEnB;gBAAaE;YAAgB;YAC5CJ;YACAsB,QAAQ;YACR,0DAA0D;YAC1DC,gBAAgB;QAClB;IACF;AACF,EAAC"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/storage/buildR2Storage.ts"],"sourcesContent":["import type { Plugin } from 'payload'\n\ntype GenerateFileURL = (args: { filename: string; prefix?: string }) => string\n\n/**\n * Minimal shape of `s3Storage` from @payloadcms/storage-s3 — the plugin never\n * imports that package (it's optional: projects on local disk don't install it).\n * The project injects the real function; TypeScript checks it fits this shape.\n */\nexport type S3StorageFactory = (options: {\n bucket: string\n collections: Record\n config: {\n credentials: { accessKeyId: string; secretAccessKey: string }\n endpoint: string\n forcePathStyle: boolean\n region: string\n }\n}) => Plugin\n\nexport type BuildR2StorageDeps = {\n /** `import { s3Storage } from '@payloadcms/storage-s3'` — required when R2 env is set. */\n s3Storage?: S3StorageFactory\n}\n\n/**\n * Cloudflare R2 media storage — configured from environment variables (agency\n * infrastructure, not per-project panel data). R2 is S3-compatible, so we use\n * @payloadcms/storage-s3 pointed at the R2 endpoint.\n *\n * Storage is infrastructure (like the database or PAYLOAD_SECRET): it binds at\n * boot, and its credentials are agency-owned — so it lives in .env, not the\n * panel. See docs/storage.md for the required variables.\n *\n * Returns the storage plugin when all R2 vars are present; otherwise returns a\n * no-op passthrough so the project falls back to Payload's default local disk\n * storage (useful in dev without R2). This mirrors how mailAdapter degrades\n * gracefully when a transport isn't configured.\n *\n * The S3 adapter is INJECTED by the project (same pattern as 2FA / NextResponse):\n *\n * import { s3Storage } from '@payloadcms/storage-s3'\n * plugins: [buildR2Storage(['media'], { s3Storage })]\n *\n * A static import here would make @payloadcms/storage-s3 mandatory for every\n * project — including ones on local disk — because this module is exported\n * from the package's main entry.\n *\n * @param collections - slugs of upload collections to offload to R2 (e.g. ['media'])\n * @param deps - `{ s3Storage }` from @payloadcms/storage-s3 (needed only when R2 env is set)\n */\nexport const buildR2Storage = (\n collections: string[] = ['media'],\n deps: BuildR2StorageDeps = {},\n): Plugin => {\n const bucket = process.env.R2_BUCKET\n const endpoint = process.env.R2_ENDPOINT\n const accessKeyId = process.env.R2_ACCESS_KEY_ID\n const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY\n\n // Any missing → skip R2, fall back to local disk. Warn so it's not silent.\n if (!bucket || !endpoint || !accessKeyId || !secretAccessKey) {\n return (config) => {\n // Only warn when SOME vars are set (partial config = likely a mistake).\n if (bucket || endpoint || accessKeyId || secretAccessKey) {\n console.warn(\n '[ipal] R2 storage: incomplete env (need R2_BUCKET, R2_ENDPOINT, ' +\n 'R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY). Falling back to local disk.',\n )\n }\n return config\n }\n }\n\n // Public URL for served media. R2 is private by default; its S3 endpoint only\n // accepts uploads and won't serve files (403). With a custom domain\n // (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs\n // pointing there. Without it, uploads work but images don't display publicly.\n // See docs/storage.md.\n const publicUrl = process.env.R2_PUBLIC_URL?.replace(/\\/$/, '') // strip trailing slash\n\n // generateFileURL is a PER-COLLECTION option in @payloadcms/storage-s3 (not a\n // top-level one) — R2 needs it to point served URLs at the custom domain\n // instead of the private S3 endpoint. Each collection gets either `true`\n // (plain offload) or an object carrying generateFileURL when a public URL is set.\n const generateFileURL = publicUrl\n ? ({ filename, prefix }: { filename: string; prefix?: string }) =>\n [publicUrl, prefix, filename].filter(Boolean).join('/')\n : undefined\n\n // R2 env is complete → the adapter is required. Fail loudly at boot rather\n // than silently storing media on the container disk (lost on redeploy).\n const { s3Storage } = deps\n if (!s3Storage) {\n throw new Error(\n '[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' +\n \"Install @payloadcms/storage-s3 and pass it: buildR2Storage(['media'], { s3Storage }) \" +\n \"with `import { s3Storage } from '@payloadcms/storage-s3'`. See docs/storage.md.\",\n )\n }\n\n const collectionsConfig: Record = {}\n for (const slug of collections) {\n collectionsConfig[slug] = generateFileURL ? { generateFileURL } : true\n }\n\n return s3Storage({\n bucket,\n collections: collectionsConfig,\n config: {\n credentials: { accessKeyId, secretAccessKey },\n endpoint,\n region: 'auto', // R2 uses 'auto'\n // R2 requires path-style addressing for S3 compatibility.\n forcePathStyle: true,\n },\n })\n}\n"],"names":["buildR2Storage","collections","deps","bucket","process","env","R2_BUCKET","endpoint","R2_ENDPOINT","accessKeyId","R2_ACCESS_KEY_ID","secretAccessKey","R2_SECRET_ACCESS_KEY","config","console","warn","publicUrl","R2_PUBLIC_URL","replace","generateFileURL","filename","prefix","filter","Boolean","join","undefined","s3Storage","Error","collectionsConfig","slug","credentials","region","forcePathStyle"],"mappings":"AAyBA;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GACD,OAAO,MAAMA,iBAAiB,CAC5BC,cAAwB;IAAC;CAAQ,EACjCC,OAA2B,CAAC,CAAC;IAE7B,MAAMC,SAASC,QAAQC,GAAG,CAACC,SAAS;IACpC,MAAMC,WAAWH,QAAQC,GAAG,CAACG,WAAW;IACxC,MAAMC,cAAcL,QAAQC,GAAG,CAACK,gBAAgB;IAChD,MAAMC,kBAAkBP,QAAQC,GAAG,CAACO,oBAAoB;IAExD,2EAA2E;IAC3E,IAAI,CAACT,UAAU,CAACI,YAAY,CAACE,eAAe,CAACE,iBAAiB;QAC5D,OAAO,CAACE;YACN,wEAAwE;YACxE,IAAIV,UAAUI,YAAYE,eAAeE,iBAAiB;gBACxDG,QAAQC,IAAI,CACV,qEACE;YAEN;YACA,OAAOF;QACT;IACF;IAEA,8EAA8E;IAC9E,oEAAoE;IACpE,yEAAyE;IACzE,8EAA8E;IAC9E,uBAAuB;IACvB,MAAMG,YAAYZ,QAAQC,GAAG,CAACY,aAAa,EAAEC,QAAQ,OAAO,IAAI,uBAAuB;;IAEvF,8EAA8E;IAC9E,yEAAyE;IACzE,yEAAyE;IACzE,kFAAkF;IAClF,MAAMC,kBAAkBH,YACpB,CAAC,EAAEI,QAAQ,EAAEC,MAAM,EAAyC,GAC1D;YAACL;YAAWK;YAAQD;SAAS,CAACE,MAAM,CAACC,SAASC,IAAI,CAAC,OACrDC;IAEJ,2EAA2E;IAC3E,wEAAwE;IACxE,MAAM,EAAEC,SAAS,EAAE,GAAGxB;IACtB,IAAI,CAACwB,WAAW;QACd,MAAM,IAAIC,MACR,6EACE,0FACA;IAEN;IAEA,MAAMC,oBAAiF,CAAC;IACxF,KAAK,MAAMC,QAAQ5B,YAAa;QAC9B2B,iBAAiB,CAACC,KAAK,GAAGV,kBAAkB;YAAEA;QAAgB,IAAI;IACpE;IAEA,OAAOO,UAAU;QACfvB;QACAF,aAAa2B;QACbf,QAAQ;YACNiB,aAAa;gBAAErB;gBAAaE;YAAgB;YAC5CJ;YACAwB,QAAQ;YACR,0DAA0D;YAC1DC,gBAAgB;QAClB;IACF;AACF,EAAC"} \ No newline at end of file diff --git a/dist/modules/storage/index.d.ts b/dist/modules/storage/index.d.ts index 2ec10de..7530f59 100644 --- a/dist/modules/storage/index.d.ts +++ b/dist/modules/storage/index.d.ts @@ -1 +1,2 @@ export { buildR2Storage } from './buildR2Storage.js'; +export type { BuildR2StorageDeps, S3StorageFactory } from './buildR2Storage.js'; diff --git a/dist/modules/storage/index.js.map b/dist/modules/storage/index.js.map index 15c8422..7747a08 100644 --- a/dist/modules/storage/index.js.map +++ b/dist/modules/storage/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/storage/index.ts"],"sourcesContent":["export { buildR2Storage } from './buildR2Storage.js'\n"],"names":["buildR2Storage"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAqB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/storage/index.ts"],"sourcesContent":["export { buildR2Storage } from './buildR2Storage.js'\nexport type { BuildR2StorageDeps, S3StorageFactory } from './buildR2Storage.js'\n"],"names":["buildR2Storage"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAqB"} \ No newline at end of file diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 040939d..593dd5f 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -150,8 +150,11 @@ Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`, dynamiczna → metadata w body. 5. **`htmlLimitedBots`** w `next.config.ts` (seo.md). 6. **Nie czytaj `searchParams`** w stronie bez paginacji — deoptymalizuje - ISR/SSG. Nie czytaj `headers()` w komponentach bloków (to samo). Locale do - bloków wstrzykuj przez `enhanceProps`. + ISR/SSG. **Nie czytaj `headers()` / `cookies()`** nigdzie w drzewie stron + statycznych — w blokach, komponentach, layoucie `[locale]` ani w + `not-found.tsx` (Next 16: `Page changed from static to dynamic at runtime`). + Locale do bloków → `enhanceProps`; w `not-found.tsx` (brak `params`) → + wersja na każdy język + `` (pages.md). 7. **`export const dynamic = 'force-dynamic'`** na trasach czytających bazę: `manifest.ts`, `sitemap.ts`/`sitemap.xml`, `llms.txt`, `api/health`. Handlery pluginu mają try/catch, ale `dynamic` musi być w pliku trasy. diff --git a/docs/agent/skills/ipal-audit/scripts/audit.sh b/docs/agent/skills/ipal-audit/scripts/audit.sh index 9f08a50..b8e2afe 100644 --- a/docs/agent/skills/ipal-audit/scripts/audit.sh +++ b/docs/agent/skills/ipal-audit/scripts/audit.sh @@ -69,9 +69,12 @@ for r in src/app/sitemap.ts src/app/manifest.ts src/app/llms.txt/route.ts src/ap report ERROR "DB route without force-dynamic" "§4.7 build without DB will crash" "$r" done -report ERROR "headers() in blocks/components" "§4.6 forces dynamic rendering — pass locale via enhanceProps" \ +report ERROR "headers()/cookies() in blocks/components" "§4.6 forces dynamic rendering — pass locale via enhanceProps" \ "$( [ -n "$UI" ] && g "from 'next/headers'" $UI)" +report ERROR "headers()/cookies() in static page tree" "§4.6 SSG/ISR → 'Page changed from static to dynamic' — not-found: LocaleView (pages.md)" \ + "$(g "from 'next/headers'" src/app --include=page.tsx --include=layout.tsx --include=not-found.tsx --include=template.tsx | grep -v '/api/\|(payload)')" + # --- Hardcoding & types (§2, §8) --- report ERROR "hardcoded locale map / any / ts-ignore" "§2, §8" \ "$(g 'localizedRoutes|as any\b|@ts-ignore|: any\b' src --include=*.ts --include=*.tsx | grep -v '/payload-types.ts:')" diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index 28f3f69..1742348 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -27,7 +27,7 @@ poniżej i doczytaj po `pnpm add`). Reguły: `docs/agent/AGENT.md`. Impeccable albo załóż neutralne tokeny), `@source` na plugin (AGENT.md §6.11). 6. **Routing** — `proxy.ts` (`createProxy`), `lib/content.ts`, layout bez ``, catch-all z ISR + `generateStaticParams` + `resolveRedirect`, - `not-found.tsx` (PROGRAMISTA §2.6–2.8). + `not-found.tsx` z `LocaleView` — bez `headers()`, wersja na każdy język (PROGRAMISTA §2.6–2.8, pages.md). 7. **SEO i bezpieczeństwo** — sitemap, robots, manifest, llms.txt, health (wszystkie z `force-dynamic`), `htmlLimitedBots`, `buildSecurityHeaders`, `instrumentation.ts` z `assertEnv` (PROGRAMISTA §2.8–2.9). diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index 78d980b..67083fc 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -168,6 +168,8 @@ export const proxy = createProxy(i18nConfig, { NextResponse }) export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } ``` Ustawia `x-locale` / `x-pathname`, cookie języka za zgodą, przekierowuje `/`. +Nagłówki są dla tras dynamicznych (API, route handlery) — w stronach SSG/ISR, +layoutach i `not-found.tsx` **nie czytaj `headers()`** (AGENT.md §4.6). ### 2.7 Warstwa danych — jedno źródło ```ts diff --git a/docs/dev/agent.md b/docs/dev/agent.md deleted file mode 100644 index 451407d..0000000 --- a/docs/dev/agent.md +++ /dev/null @@ -1,1223 +0,0 @@ -# AGENT.md — reguły dla AI (Payload 3 + Next 16 + @intecion/ipal-kit) - -> **Dla kogo:** agent AI (Antigravity, Claude Code, Cursor) pracujący w projekcie -> klienta na ipal-kit. **Przeczytaj w całości przed pierwszą zmianą.** Reguły są -> twarde, bez obejść. Szczegóły API każdego modułu: `docs/.md` (mapa w -> §12). Instalacja, wdrożenie, migracja i Gitea to dokument dla ludzi: -> [PROGRAMISTA.md](../dev/PROGRAMISTA.md). -> -> **W projekcie:** -> - w roocie krótki `AGENTS.md` (szablon w §13), który wskazuje na ten plik w - > `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` — nie kopiuj reguł, kopia się zestarzeje; -> - skille w `.agents/skills/` (§14) — kopiowane z pakietu jedną komendą, odświeżane - > po każdej aktualizacji ipal-kit. - ---- - -## 0. KOMPAS (jeśli zapamiętasz tylko to) - -1. **ipal-kit jest obowiązkowy.** Funkcja, którą plugin ma, idzie przez plugin. - Brakuje czegoś → zgłoś (§1.3), nie łataj w projekcie. -2. **Nic na sztywno.** Tekst, obraz, link, plik, dane firmy → panel. Domeny, - klucze → `.env`. Także w fallbacku `||` i w `catch`. -3. **Next 16 = `proxy.ts`.** NIGDY `middleware.ts`. -4. **Bez jawnego ``, z ISR i `generateStaticParams`** — inaczej metadata - ląduje w `` i SEO pada. -5. **Minimum kolekcji.** Users są wbudowane, dane firmy/nawigacja to globale, - FAQ/hero to bloki. -6. **Sekcja = kompozycja prymitywów.** `linksField()` + ``, upload + - ``, `
` + ``. Zero pól `ctaLabel`/`pdfUrl`. -7. **Renderery z pluginu:** `RenderBlocks` (nie `switch`), `RenderRichText` (nie - własny parser Lexical), `useForm` (nie ręczna hydraulika formularza). -8. **Zero `any` i `@ts-ignore`.** Typy z `@/payload-types`, `unknown` + guard. -9. **Jedno źródło prawdy** — `i18n.config.ts`, `lib/content.ts`, nigdy kopie. -10. **„Gotowe” dopiero po** lokalnym `pnpm build` + kontrolach z §11. - ---- - -## 1. ipal-kit JEST OBOWIĄZKOWY - -### 1.1 Zanim napiszesz cokolwiek -Sprawdź, czy plugin to ma: docs modułu (§12) i typy -`node_modules/@intecion/ipal-kit/dist/**/*.d.ts`. Nie zgaduj sygnatur. Jeśli -plugin to ma — użyj go. Własna wersja istniejącej funkcji pluginu to błąd. - -### 1.2 Co należy do pluginu, a co do projektu -Reguła: **identyczne w każdym projekcie → plugin. Zależy od klienta → projekt.** - -| Plugin (używasz) | Projekt (piszesz) | -|---|---| -| i18n, routing, slug, SEO meta, sitemap, hreflang | bloki: schemat + wygląd | -| formularze, zgoda RODO, Turnstile, email | globale Company/Header/Footer (model danych zależy od kraju: NIP/ABN/EIN) | -| consent, analytics/pixele | CSP (domeny projektu) | -| nagłówki bezpieczeństwa, 2FA, white-label | schema.org: mapowanie SWOICH danych na `@type` | -| hooki (revalidate, slugHistory, cross-locale), strony systemowe, storage R2 | wygląd (Tailwind, DESIGN.md) | - -### 1.3 Gdy w pluginie czegoś brakuje albo nie działa -**Zatrzymaj się. Nie łataj w projekcie** (hook z zaszytą wartością, własny -helper, `as any`). To prawie zawsze znak, że plugin już to ma (sprawdź docs) albo -pluginowi tego brakuje. Przygotuj raport: -- opis problemu / brakującej funkcji, -- proponowane API (sygnatura funkcji / opcji), -- dlaczego to uniwersalne (przyda się w innych projektach). - -Realne błędy: hook `afterRead` w Media z `https://media.klient.pl` (plugin generuje -URL z `R2_PUBLIC_URL`), `` z zaszytą domeną (plugin ma -``), skopiowany komponent `Analytics` w projekcie z usuniętym -gatingiem zgody (plugin ma opcję `defer`). - ---- - -## 2. ZAKAZ HARDKODOWANIA - -| Co | ZAKAZ | WYMAGANE | -|---|---|---| -| Tekst | tekst w JSX, `if (locale === 'pl')`, tablice tekstów w kodzie | pole `localized: true` z panelu | -| Obraz / plik | `import x from '@/assets/…'`, `src="/images/…"`, URL pliku w polu `text` | `upload → media` + `` / link typu `file` | -| Link | `href="/pl/kontakt"`, menu jako tablica, mapa `localizedRoutes` | `linkField()` + ``, `getLocalizedSlugs`, `getSystemPagePath`, nawigacja jako relationship → pages | -| Konfiguracja | `locale as 'pl' \| 'en'`, zaszyty slug kolekcji, lista języków `['pl','en']` | `i18n.config.ts`, `locale as never`, lista z configu | -| Dane firmy | NIP, adres, telefon, nazwa w kodzie | global (`siteSettings` / `company`) | -| Infrastruktura | domena, klucz, bucket w kodzie | `.env` | - -**Ukryty hardkod w fallbacku (częsty):** `siteName || 'Kancelaria X'`, -`catch { return { name: 'Firma…' } }`, `theme_color: '#0e1e24'`. Gdy panel nie -zwróci danych → **pomiń pole** (`...(name ? { name } : {})`), nie wstawiaj -wartości klienta. Inny projekt skopiuje kod i pokaże cudze dane. - -Favicon: `buildIconsMetadata(settings.favicon)` (PNG, nie ręczny SVG). -Preconnect CDN: `` (z env). Media: `normalizeFilenameHook`. - ---- - -## 3. STRUKTURA PROJEKTU I NAZEWNICTWO - -``` -src/ - app/ - (frontend)/ - styles.css # Tailwind + @source na node_modules/@intecion/ipal-kit/dist - [locale]/ # jednojęzyczny: bez [locale] (patrz i18n.md) - layout.tsx # bez ; ConsentProvider + Analytics - not-found.tsx # 404 z panelu (getNotFoundPage) - [[...slug]]/page.tsx # PODWÓJNE nawiasy; RenderBlocks - (payload)/ # panel (generowany) - manifest.ts # createManifestHandler + force-dynamic - sitemap.ts, robots.ts # z lib/content (+ force-dynamic na sitemap) - api/health/route.ts # createHealthRoute - instrumentation.ts # assertEnv(ipalEnvRules({...})) - fields/ # wspólne pola: link.ts, sectionHeader.ts, sectionSettings.ts - components/ - ui/ # prymitywy: CMSLink, Button, Media, Section, SectionHeader - layout/ # Header, Footer, MobileNav (§6.8) - icons/ # names.ts + Icon.tsx (§6.10) - blocks// # config.ts + Component.tsx (+ XxxCard.tsx, klienckie obok) - blocks/registry.ts # blockType → komponent - collections/ # Pages.ts, Media.ts (+ treść tylko gdy wymagana) - globals/ # Header.ts, Footer.ts, Company.ts - lib/content.ts # createContentHelpers — JEDYNY dostęp do Payloada - lib/links.ts # resolveLinkHref - lib/navigation.ts # resolveNav → dane dla menu - i18n.config.ts # locale — jedno źródło - payload.config.ts - proxy.ts # NIE middleware.ts -``` - -| Element | Konwencja | Przykład | -|---|---|---| -| Folder bloku, kolekcja, global | PascalCase | `blocks/FeatureGrid/`, `collections/Pages.ts` | -| Helper, plik lib | camelCase | `lib/content.ts` | -| Slug kolekcji | camelCase, l.mn. | `pages`, `blogPosts` | -| Slug bloku = klucz w registry | camelCase | `hero`, `featureGrid` | -| Nazwa pola | camelCase, słownictwo z §6.5 | `header`, `links`, `media` | -| Komponent | nazwana funkcja, typy z `@/payload-types` | `export function Hero(...)` | - -Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`, -`lib/locales.ts` — plugin ma `resolveRoute`, `getConfiguredLocales`. - ---- - -## 4. NEXT 16 — RENDERING, SEO, BUILD - -1. **`proxy.ts`, nigdy `middleware.ts`.** Istnieje middleware.ts → usuń. Proxy: - `export const proxy = createProxy(i18nConfig, { NextResponse })`, matcher - jako **literał inline** (`['/((?!api|admin|_next|.*\\..*).*)']`), nie import. -2. **Bez jawnego `` w layoutcie.** Wypycha metadata do ``. - `` w `` (React 19 hoistuje). -3. **ISR:** `export const revalidate = 3600` w `page.tsx`. Odświeżanie po zapisie: - `buildRevalidateHook` (hooks.md). -4. **`generateStaticParams`** w `[[...slug]]/page.tsx`: - `export { generateStaticParams } from '@/lib/content'`. Trasa bez niego jest - dynamiczna → metadata w body. -5. **`htmlLimitedBots`** w `next.config.ts` (seo.md). -6. **Nie czytaj `searchParams`** w stronie bez paginacji — deoptymalizuje - ISR/SSG. Nie czytaj `headers()` w komponentach bloków (to samo). Locale do - bloków wstrzykuj przez `enhanceProps`. -7. **`export const dynamic = 'force-dynamic'`** na trasach czytających bazę: - `manifest.ts`, `sitemap.ts`/`sitemap.xml`, `llms.txt`, `api/health`. Handlery - pluginu mają try/catch, ale `dynamic` musi być w pliku trasy. -8. **`instrumentation.ts`** z `assertEnv(ipalEnvRules({...}))` (env.md). -9. **RSC domyślnie.** `'use client'` tylko dla stanu/interakcji, w osobnym pliku; - sekcja zostaje serwerowa i podaje mu dane. Sekrety: `import 'server-only'`. -10. **Bloki nie importują `lib/*`** (cykl). Dane server-side → `enhanceProps`. - ---- - -## 5. MODEL TREŚCI — CO JEST CZYM - -### 5.1 Zasada nadrzędna -**Wszystko, co widać na stronie, redaktor zmienia w panelu** — nagłówki, -akapity, przyciski (tekst i cel), obrazy, pliki, kolejność sekcji, SEO, teksty -formularza i banera, dane kontaktowe. Deweloper dostarcza klocki (bloki), -redaktor składa z nich strony. Nowa strona = zero kodu. - -### 5.2 Kolekcja, global czy blok? -- **Blok** — część strony (hero, FAQ, galeria, CTA, opinie w sekcji). -- **Global** — jeden zestaw na serwis (nawigacja, stopka, dane firmy, ustawienia). -- **Kolekcja** — lista rekordów, każdy z **własnym URL** (post, produkt, realizacja). - -### 5.3 MINIMUM kolekcji -Domyślnie: `pages`, `media` + globale pluginu (`site-settings`, -`site-integrations`, Notifications, Cookie Settings) + globale projektu -(nawigacja, stopka, firma). Nic więcej, dopóki klient jawnie nie wymaga. - -**NIGDY:** `users` (wbudowane w Payload), druga `media`, `daneFirmy`/`settings`/ -`navigation`/`footer` jako kolekcje (to globale), FAQ/hero/features jako kolekcje -(to bloki), kolekcja dla jednej rzeczy (to strona albo global). - -**Test przed nową kolekcją — wszystkie muszą być TAK:** lista wielu rekordów? -każdy ma własny URL? klient jawnie wymaga? Payload tego nie ma wbudowanego? - -Typowe kolekcje treści (gdy wymagane): `posts`/`blogPosts` (+ `authors`, -`categories`), `products`, `projects` (portfolio). Opinie (`testimonials`) bez -własnych URL-i → nie dodawaj do `content`. - -### 5.4 Wpięcie kolekcji z URL-ami -```ts -// ipalKit({ content: contentConfig }) i createContentHelpers({ content: contentConfig }) -export const contentConfig = { - collections: [{ slug: 'posts', perPage: 10 }], -} satisfies ContentOption -``` -Prefiks URL **nie jest w kodzie** — redaktor przypisuje stronę-archiwum w Site -Settings (`postsArchive`). Zmiana jej sluga przenosi całą sekcję, per język. -Plugin robi routing (`resolveRoute`), sitemap, `generateStaticParams`, hreflang. -Każda kolekcja treści: `title`, `buildSlugField`, tab SEO, `buildNoindexField`, -`trackSlugHistoryHook`, structured data jeśli dotyczy (seo.md). Szczegóły: content.md. - -### 5.5 Strony systemowe -Site Settings → System Pages: `homepage`, `notFound` (404), `privacyPolicy`, -`cookiePolicy`, `termsOfService`. Linkuj przez rolę (`getSystemPagePath`), -nigdy po slugu. pages.md. - ---- - -## 6. BUDOWA SEKCJI (bloki `.tsx`) - -Trzy problemy, których nie wolno powtarzać: **zoo pól CTA** (`ctaLabel`, -`cta2Text`, `buttonUrl`…), **pliki jako tekst** (`pdfUrl: '/files/x.pdf'`), -**sekcja-monolit** (200–400 linii z kartami, ikonami SVG i stylami przycisków). - -### 6.1 Trzy warstwy -``` -src/fields/ WARSTWA 1 — wspólne pola schematu (link, header, settings) -src/components/ui/ WARSTWA 2 — prymitywy UI (CMSLink, Button, Media, Section, SectionHeader) -src/blocks/X/ WARSTWA 3 — sekcja = kompozycja warstw 1 i 2 -``` -Zmiana wyglądu przycisku w całym serwisie = jedna zmiana w `Button.tsx`. Jeśli -musisz zmieniać 12 bloków, architektura jest zła. - -### 6.2 Warstwa 1 — wspólne pola - -`src/fields/link.ts` — **jedyny sposób na link/CTA**: - -```ts -import type { ArrayField, Field, GroupField } from 'payload' - -export type LinkAppearance = 'primary' | 'secondary' | 'link' - -type LinkFieldOptions = { - name?: string - /** Which visual styles the editor may pick. false → no appearance select. */ - appearances?: LinkAppearance[] | false - /** Label hidden for links that wrap something (a card, an image). */ - disableLabel?: boolean - required?: boolean -} - -const URL_PATTERN = /^(https?:\/\/|mailto:|tel:|#)/ - -export function linkField({ - name = 'link', - appearances = ['primary', 'secondary', 'link'], - disableLabel = false, - required = false, -}: LinkFieldOptions = {}): GroupField { - const fields: Field[] = [ - { - type: 'row', - fields: [ - { - name: 'type', - type: 'radio', - defaultValue: 'internal', - options: [ - { label: 'Page', value: 'internal' }, - { label: 'URL', value: 'external' }, - { label: 'File', value: 'file' }, - ], - admin: { layout: 'horizontal', width: '50%' }, - }, - { - name: 'newTab', - type: 'checkbox', - label: 'Open in new tab', - admin: { width: '50%', style: { alignSelf: 'flex-end' } }, - }, - ], - }, - { - name: 'page', - type: 'relationship', - relationTo: 'pages', - required, - admin: { condition: (_, s) => s?.type === 'internal' }, - }, - { - name: 'url', - type: 'text', - required, - validate: (v: string | null | undefined) => - !v || URL_PATTERN.test(v) || 'Use https://…, mailto:, tel: or #anchor', - admin: { - condition: (_, s) => s?.type === 'external', - description: 'Full URL (https://…), mailto:, tel: or #section-anchor.', - }, - }, - { - name: 'file', - type: 'upload', - relationTo: 'media', - required, - admin: { - condition: (_, s) => s?.type === 'file', - description: 'Upload a PDF / document / image. Never paste a file URL.', - }, - }, - ] - - if (!disableLabel) { - fields.push({ name: 'label', type: 'text', localized: true, required }) - } - - if (appearances && appearances.length) { - fields.push({ - name: 'appearance', - type: 'select', - defaultValue: appearances[0], - options: appearances.map((a) => ({ label: a, value: a })), - }) - } - - return { - name, - type: 'group', - interfaceName: 'CmsLink', // → `CmsLink` type in payload-types.ts - admin: { hideGutter: true }, - fields, - } -} - -/** 0..N buttons. Use this for every "CTA(s)" in a section. */ -export function linksField({ - name = 'links', - maxRows = 2, - appearances, -}: { name?: string; maxRows?: number; appearances?: LinkAppearance[] } = {}): ArrayField { - return { - name, - type: 'array', - maxRows, - admin: { initCollapsed: true }, - fields: [linkField({ appearances })], - } -} -``` - -Całe CTA w bloku to jedna linia: `linksField()`. Karta klikalna w całości: -`linkField({ disableLabel: true, appearances: false })`. - -**Pliki i obrazy:** `{ name: 'media', type: 'upload', relationTo: 'media' }`. -Kolekcja `media` dopuszcza PDF (`upload.mimeTypes: ['image/*', 'application/pdf', -'video/mp4']`), ma `alt` (required, localized) i `normalizeFilenameHook`. -„Pobierz cennik (PDF)” to **link typu `file`**, nie osobne pole `pdf`/`pdfUrl`. - -`src/fields/sectionHeader.ts` i `src/fields/sectionSettings.ts`: - -```ts -import type { GroupField } from 'payload' - -export function sectionHeaderField(name = 'header'): GroupField { - return { - name, - type: 'group', - interfaceName: 'SectionHeaderData', - fields: [ - { name: 'eyebrow', type: 'text', localized: true }, - { name: 'heading', type: 'text', localized: true }, - { name: 'intro', type: 'textarea', localized: true }, - ], - } -} - -export function sectionSettingsField(): GroupField { - return { - name: 'settings', - type: 'group', - interfaceName: 'SectionSettings', - admin: { position: 'sidebar' }, - fields: [ - { - name: 'anchor', - type: 'text', - admin: { description: 'Section id for #links and section nav, e.g. "pricing".' }, - }, - { - name: 'background', - type: 'select', - defaultValue: 'default', - options: ['default', 'muted', 'inverted'].map((v) => ({ label: v, value: v })), - }, - ], - } -} -``` - -Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `darkMode`, -`sectionId` w poszczególnych blokach. Etykiety pól po angielsku (panel jest EN). - -### 6.3 Warstwa 2 — prymitywy UI - -`src/lib/links.ts` — jedyne miejsce, które zna typy linków: - -```ts -import type { CmsLink } from '@/payload-types' -import { buildLocalizedPath } from '@intecion/ipal-kit' -import { i18nConfig } from '@/i18n.config' - -export function resolveLinkHref( - link: CmsLink | null | undefined, - locale: string, - homeSlug?: string, -): string | null { - if (!link) return null - if (link.type === 'external') return link.url || null - if (link.type === 'file') { - const file = link.file - return file && typeof file === 'object' && file.url ? file.url : null - } - // internal — `page` must be populated (block depth ≥ 2), not a bare ID - const page = link.page - if (!page || typeof page !== 'object' || typeof page.slug !== 'string') return null - return ( - buildLocalizedPath({ - slugs: { [locale]: page.slug }, - locale, - config: i18nConfig, - ...(homeSlug ? { homeSlug } : {}), - }) ?? null - ) -} -``` - -`src/components/ui/CMSLink.tsx` — **każdy** link/przycisk z panelu: - -```tsx -import Link from 'next/link' -import type { ReactNode } from 'react' -import type { CmsLink } from '@/payload-types' -import { resolveLinkHref } from '@/lib/links' -import { getSettings } from '@/lib/content' -import { buttonClass } from './Button' - -type Props = { - link: CmsLink | null | undefined - locale: string - className?: string - /** For wrapping links (cards): content instead of link.label. */ - children?: ReactNode -} - -export async function CMSLink({ link, locale, className, children }: Props) { - const settings = await getSettings(locale) // react cache → one query per request - const home = settings?.homepage - const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined - - const href = resolveLinkHref(link, locale, homeSlug) - const content = children ?? link?.label - if (!link || !href || !content) return null - - const cls = [link.appearance ? buttonClass(link.appearance) : '', className] - .filter(Boolean) - .join(' ') - const newTab = link.newTab || link.type === 'file' - const targetProps = newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {} - - if (link.type === 'internal') { - return {content} - } - return {content} -} -``` - -`src/components/ui/Button.tsx` — warianty jako mapa, nie ternary: - -```ts -import type { LinkAppearance } from '@/fields/link' - -const VARIANTS: Record = { - primary: 'btn btn-primary', - secondary: 'btn btn-secondary', - link: 'link-arrow', -} - -export function buttonClass(appearance: LinkAppearance): string { - return VARIANTS[appearance] -} -``` - -`src/components/ui/Media.tsx` — **każdy** obraz/wideo z panelu: - -```tsx -import Image from 'next/image' -import type { Media as MediaDoc } from '@/payload-types' - -type Props = { - resource: MediaDoc | string | number | null | undefined - sizes?: string - priority?: boolean - className?: string -} - -export function Media({ resource, sizes = '100vw', priority = false, className }: Props) { - if (!resource || typeof resource !== 'object' || !resource.url) return null - const { url, alt, width, height, mimeType } = resource - - if (mimeType?.startsWith('video/')) { - return