Fixed notfound headers, r2storage

This commit is contained in:
2026-10-13 15:57:59 +02:00
parent 86c873e4e7
commit 786dd346a9
24 changed files with 1506 additions and 2765 deletions
+3 -2
View File
@@ -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 <LocaleView> (client) pick the one from the URL. See pages.md.
*/ const getNotFoundPage = cache(async (locale)=>{
try {
const payload = await getCachedPayload();
File diff suppressed because one or more lines are too long
+21
View File
@@ -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: <RenderBlocks …/>, 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<string, ReactNode>;
};
/**
* 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 {};
+23
View File
@@ -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
+1
View File
@@ -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: <RenderBlocks …/>, 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<string, ReactNode>\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"}
+40 -1
View File
@@ -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<string, {
generateFileURL: GenerateFileURL;
} | true>;
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 {};
+17 -2
View File
@@ -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 ? {
File diff suppressed because one or more lines are too long
+1
View File
@@ -1 +1,2 @@
export { buildR2Storage } from './buildR2Storage.js';
export type { BuildR2StorageDeps, S3StorageFactory } from './buildR2Storage.js';
+1 -1
View File
@@ -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"}
{"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"}
+5 -2
View File
@@ -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 + `<LocaleView>` (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.
@@ -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:')"
+1 -1
View File
@@ -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
`<head>`, 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).
+2
View File
@@ -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
-1223
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -141,7 +141,7 @@ Zrób zgodnie z PROGRAMISTA.md §2.6–2.8 i AGENT.md §4:
ConsentProvider + CookieBanner + CookieButton + Analytics wewnątrz providera,
- [locale]/[[...slug]]/page.tsx: revalidate, generateStaticParams, BEZ searchParams,
resolveRedirect przed notFound, enhanceProps wstrzykuje locale do bloków,
- [locale]/not-found.tsx z getNotFoundPage (pages.md).
- [locale]/not-found.tsx z getNotFoundPage dla każdego języka + LocaleView, BEZ headers() (pages.md).
Plan najpierw.
```
Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`;
+24 -10
View File
@@ -62,24 +62,38 @@ Site Settings → System Pages → **404 (Not Found)**. Edytor wybiera:
- stronę główną (część klientów tak woli), **albo**
- nic → projekt pokazuje wbudowany fallback z `not-found.tsx`.
Projekt (`app/(frontend)/[locale]/not-found.tsx`) — gotowy przykład w
Projekt (`app/(frontend)/[locale]/not-found.tsx`) — pełny przykład w
`frontend/[locale]/not-found.tsx`:
```tsx
import { headers } from 'next/headers'
import { getNotFoundPage } from '@/lib/content' // z createContentHelpers
import { RenderBlocks } from '@intecion/ipal-kit/rsc'
import { LocaleView } from '@intecion/ipal-kit/client'
import { getConfiguredLocales, getNotFoundPage } from '@/lib/content'
export default async function NotFound() {
const locale = (await headers()).get('x-locale') ?? i18nConfig.defaultLocale
const page = await getNotFoundPage(locale) // null → fallback
if (page?.layout?.length) return <RenderBlocks blocks={page.layout} components={blockRegistry} />
return <Fallback404 locale={locale} />
const locales = await getConfiguredLocales()
const views = Object.fromEntries(await Promise.all(locales.map(async (locale) => {
const page = await getNotFoundPage(locale) // null → brak przypisania
return [locale, page?.layout?.length
? <RenderBlocks blocks={page.layout} components={blockRegistry} enhanceProps={() => ({ locale })} />
: null]
})))
return <LocaleView views={views} defaultLocale={i18nConfig.defaultLocale} />
}
```
`not-found.tsx` nie dostaje `params` — locale bierzemy z nagłówka `x-locale`,
który ustawia proxy z `createProxy`. Status HTTP zostaje **404** (renderuje go
Next po `notFound()`), treść jest z panelu.
> **NIE czytaj `headers()` w `not-found.tsx`** (`LocaleView` od 1.7.13). `not-found.tsx` nie dostaje
> `params`, ale `headers()` (np. `x-locale` z proxy) zamienia stronę SSG/ISR w
> dynamiczną — Next 16 rzuca `Page changed from static to dynamic at runtime`
> (AGENT.md §4.6). Dlatego serwer renderuje stronę 404 **dla każdego języka**
> (same odczyty z bazy — trasa zostaje statyczna), a `<LocaleView>` (komponent
> kliencki pluginu) wybiera wersję po pierwszym segmencie URL (`usePathname`).
> Działa też przy SSR — HTML ma od razu właściwy język. Layout `[locale]`
> (nagłówek, menu, stopka) i tak dostaje `params.locale` z URL.
Status HTTP zostaje **404** (renderuje go Next po `notFound()`), treść jest z
panelu we właściwym języku. Koszt: w payloadzie RSC strony 404 są wersje dla
wszystkich języków — przy stronie 404 to pomijalne.
Co plugin robi automatycznie z przypisaną stroną 404:
+51
View File
@@ -0,0 +1,51 @@
import React from 'react'
import { RenderBlocks } from 'ipal-kit/rsc'
import { LocaleView } from 'ipal-kit/client'
import { i18nConfig } from '@/i18n.config'
import { blockRegistry } from '@/blocks/registry'
import { getConfiguredLocales, getNotFoundPage } from '@/lib/content'
/**
* 404 view. The editor picks which page plays the 404 role in
* Site Settings → System Pages → "404 (Not Found)" — a dedicated page or the
* homepage — or leaves it empty → the fallback below.
*
* not-found.tsx receives no params, and reading headers() here would turn the
* SSG/ISR site dynamic ("Page changed from static to dynamic at runtime").
* So: render the 404 page for EVERY locale on the server (DB reads only — stays
* static) and let <LocaleView> pick the one from the URL (/en/... → en).
* Next still answers HTTP 404.
*/
export default async function NotFound() {
const locales = await getConfiguredLocales()
const views = Object.fromEntries(
await Promise.all(
locales.map(async (locale) => {
const page = (await getNotFoundPage(locale)) as { layout?: unknown[] } | null
const view = page?.layout?.length ? (
<RenderBlocks
blocks={page.layout as never}
components={blockRegistry}
enhanceProps={() => ({ locale })}
/>
) : null
return [locale, view] as const
}),
),
)
// No 404 page assigned in any locale (or DB unreachable during build):
// the project's own minimal view — style it, keep it text-free or panel-driven.
if (Object.values(views).every((v) => v === null)) {
return (
<main className="container py-24 text-center">
<h1 className="text-6xl font-bold">404</h1>
</main>
)
}
return <LocaleView views={views} defaultLocale={i18nConfig.defaultLocale} />
}
+10 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@intecion/ipal-kit",
"version": "1.8.0",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"version": "1.7.13",
"description": "Intecion Payload Advanced Library \u2014 a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
"type": "git",
@@ -73,6 +73,9 @@
"peerDependencies": {
"@payloadcms/plugin-form-builder": "^3.90.2",
"@payloadcms/plugin-seo": "^3.90.2",
"@payloadcms/richtext-lexical": "^3.90.2",
"@payloadcms/storage-s3": "^3.90.2",
"@payloadcms/ui": "^3.90.2",
"next": ">=15",
"payload": "^3.90.2",
"react": "^19.0.0"
@@ -127,5 +130,10 @@
"esbuild",
"unrs-resolver"
]
},
"peerDependenciesMeta": {
"@payloadcms/storage-s3": {
"optional": true
}
}
}
+1161 -1458
View File
File diff suppressed because it is too large Load Diff
+57 -56
View File
@@ -74,8 +74,8 @@ export function createContentHelpers({
settingsSlug = 'site-settings',
}: CreateContentHelpersArgs) {
const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''
const getCachedPayload = cache(async (): Promise<BasePayload> =>
getPayload({ config: await config }),
const getCachedPayload = cache(
async (): Promise<BasePayload> => getPayload({ config: await config }),
)
const getConfiguredLocales = cache(async (): Promise<string[]> => {
@@ -102,8 +102,9 @@ export function createContentHelpers({
/**
* 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 <LocaleView> (client) pick the one from the URL. See pages.md.
*/
const getNotFoundPage = cache(async (locale: string) => {
try {
@@ -150,7 +151,9 @@ export function createContentHelpers({
*/
const sitemap = cache(async (): Promise<SitemapEntry[]> => {
if (!i18n) {
throw new Error('[ipal] createContentHelpers: pass `i18n` to use the sitemap handler.')
throw new Error(
'[ipal] createContentHelpers: pass `i18n` to use the sitemap handler.',
)
}
try {
return await buildSitemapEntries({
@@ -235,62 +238,60 @@ export function createContentHelpers({
const params: Array<{ locale: string; slug: string[] } | { slug: string[] }> = []
for (const locale of locales) {
// NO where:{_status} filter — collections without drafts enabled don't
// register the _status field, and querying it throws
// "path cannot be queried: _status". We filter drafts in memory below,
// which is safe for every collection (with or without drafts).
const result = await payload.find({
collection: pagesSlug as never,
depth: 0,
limit: 1000,
locale: (locale ?? 'all') as never,
})
// NO where:{_status} filter — collections without drafts enabled don't
// register the _status field, and querying it throws
// "path cannot be queried: _status". We filter drafts in memory below,
// which is safe for every collection (with or without drafts).
const result = await payload.find({
collection: pagesSlug as never,
depth: 0,
limit: 1000,
locale: (locale ?? 'all') as never,
})
for (const raw of result.docs as Array<{
_status?: string
id: number | string
meta?: { noindex?: boolean } | null
slug?: unknown
}>) {
// Draft filter in memory (safe whether or not the collection has drafts).
if (raw._status && raw._status !== 'published') {continue}
if (notFoundId !== undefined && raw.id === notFoundId) {continue}
for (const raw of result.docs as Array<{
_status?: string
id: number | string
meta?: { noindex?: boolean } | null
slug?: unknown
}>) {
// Draft filter in memory (safe whether or not the collection has drafts).
if (raw._status && raw._status !== 'published') {continue}
if (notFoundId !== undefined && raw.id === notFoundId) {continue}
// NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex
// page (privacy, cookies, terms) still needs to render — users reach it
// from the footer and crawlers read its <meta robots=noindex>. Pre-render
// it as SSG so it's fast and its <head> is complete; noindex controls
// INDEXING, not whether the page exists. Skipping it would force dynamic
// rendering (the very streaming problem we're avoiding).
// NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex
// page (privacy, cookies, terms) still needs to render — users reach it
// from the footer and crawlers read its <meta robots=noindex>. Pre-render
// it as SSG so it's fast and its <head> is complete; noindex controls
// INDEXING, not whether the page exists. Skipping it would force dynamic
// rendering (the very streaming problem we're avoiding).
if (homeId && raw.id === homeId) {
// Homepage → root. Emit an empty-slug param so '/' (or '/pl') builds.
const empty = singleLocale ? { slug: [] } : { slug: [], locale: locale as string }
if (!params.some((p) => JSON.stringify(p) === JSON.stringify(empty))) {params.push(empty)}
continue
}
// Slug may be a plain string OR a localized map ({ pl: 'kontakt' }) when
// read with locale:'all' or left unflattened. Handle both, or localized
// pages get silently dropped.
const rawSlug = raw.slug
const slug =
typeof rawSlug === 'string'
? rawSlug
: rawSlug && typeof rawSlug === 'object'
? (((rawSlug as Record<string, unknown>)[locale ?? ''] as string | undefined) ??
(Object.values(rawSlug as Record<string, unknown>)[0] as string | undefined))
: undefined
if (!slug || EXCLUDED.has(slug)) {continue}
// Multi-level slugs ('atrakcje/telefon') → array segments.
const segments = String(slug).split('/').filter(Boolean)
params.push(
singleLocale ? { slug: segments } : { slug: segments, locale: locale as string },
)
if (homeId && raw.id === homeId) {
// Homepage → root. Emit an empty-slug param so '/' (or '/pl') builds.
const empty = singleLocale ? { slug: [] } : { slug: [], locale: locale as string }
if (!params.some((p) => JSON.stringify(p) === JSON.stringify(empty))) {params.push(empty)}
continue
}
// Slug may be a plain string OR a localized map ({ pl: 'kontakt' }) when
// read with locale:'all' or left unflattened. Handle both, or localized
// pages get silently dropped.
const rawSlug = raw.slug
const slug =
typeof rawSlug === 'string'
? rawSlug
: rawSlug && typeof rawSlug === 'object'
? ((rawSlug as Record<string, unknown>)[locale ?? ''] as string | undefined) ??
(Object.values(rawSlug as Record<string, unknown>)[0] as string | undefined)
: undefined
if (!slug || EXCLUDED.has(slug)) {continue}
// Multi-level slugs ('atrakcje/telefon') → array segments.
const segments = String(slug).split('/').filter(Boolean)
params.push(singleLocale ? { slug: segments } : { slug: segments, locale: locale as string })
}
}
return params
} catch (err) {
+32
View File
@@ -0,0 +1,32 @@
'use client'
import type { ReactNode } from 'react'
// '.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'
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: <RenderBlocks …/>, 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<string, ReactNode>
}
/**
* 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 }: LocaleViewProps) {
const pathname = usePathname() ?? ''
const segment = pathname.split('/').filter(Boolean)[0] ?? ''
const locale = segment in views ? segment : defaultLocale
return <>{views[locale] ?? views[defaultLocale] ?? null}</>
}
+48 -3
View File
@@ -1,6 +1,27 @@
import type { Plugin } from 'payload'
import { s3Storage } from '@payloadcms/storage-s3'
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<string, { generateFileURL: GenerateFileURL } | true>
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
@@ -16,9 +37,22 @@ 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: string[] = ['media']): Plugin => {
export const buildR2Storage = (
collections: string[] = ['media'],
deps: BuildR2StorageDeps = {},
): Plugin => {
const bucket = process.env.R2_BUCKET
const endpoint = process.env.R2_ENDPOINT
const accessKeyId = process.env.R2_ACCESS_KEY_ID
@@ -54,7 +88,18 @@ export const buildR2Storage = (collections: string[] = ['media']): Plugin => {
[publicUrl, prefix, filename].filter(Boolean).join('/')
: undefined
const collectionsConfig: Record<string, { generateFileURL: typeof generateFileURL } | true> = {}
// 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: Record<string, { generateFileURL: GenerateFileURL } | true> = {}
for (const slug of collections) {
collectionsConfig[slug] = generateFileURL ? { generateFileURL } : true
}
+1
View File
@@ -1 +1,2 @@
export { buildR2Storage } from './buildR2Storage.js'
export type { BuildR2StorageDeps, S3StorageFactory } from './buildR2Storage.js'